Jun 16, 2011

Visual Studio and C# (Some Useful Code Samples)

Creating MDI Forms (Multiple Document Interface).

Add 2 new Forms (Form1, Form2) to the solute on. Form1 will be the main frame and Form2 will be inside the first one. So in the first one we must make it as a MDIParent form. To do that, select the Form1 and go to its properties. In that list you will see a property called “IsMdiContainer”. Set it to TRUE. Now you will see that the form has been changed. Then go to the code behind of the Form1. In the constructor of the class, you should write this code in order to view the Form2 inside the Form1.

Note: - You can use a toolStrip instead of writing the code in the constructor.
public Form1()
{
        InitializeComponent(); // This is an auto generated code.
        // start of our code.
        Form2 fm = new Form2();
        Fm.MdiParent = this;
        Fm.Show();
        // end of our code.
}
These 3 lines of code will do the trick. Think if you need to open another form (Form3) by clicking a button in Form2, so you need to modify the 2nd line of this code to,
Fm.MdiParent = this.Parent;
This will set the MdiParent for Form3, by the parent of Form2. It means that it will use the Form1 as the parent of the Form3.



Connect your .NET Application to MySQL Database.

Most of the time .Net applications will use MSSQL database. But here is a sample code to connect your application to MySQL database.

First of all you need to install MySQL connecter for .NET environment. It can be freely download from this link. (For windows and MONO project.)

http://dev.mysql.com/downloads/connector/net/

Note: - Close Visual Studio before you start installing the connector.

I will not going to create a DbAccess class here, just simply tell how to use it.

First of all you need to add a reference called “MySql.Data” to your project. Then you need to add namespace,
Using MySql.Data; 
After that I will use a button click event to get data from the MySQL database.
private void button1_Click(object sender, EventArgs e)
{        
   string result = null;

   InitializeComponent();
   string ConString = "User Id=user;"+ 
                      "password=password;"+
                      "Persist Security Info=True;"+
                      "server=localhost;"+
                      "database=test";

   MySqlConnection conn = new MySqlConnection(ConString);

   MySqlCommand cmd = conn.CreateCommand();
   cmd.CommandText = "Select * from test";
   conn.Open();

   MySqlDataReader reader = cmd.ExecuteReader();
   while (reader.Read())
   {
      result += reader["name"].ToString() + " \n ";
   }
   conn.Close();
   MessageBox.Show(result);
}


Use configuration files in Visual Studio.

In the previous sample code I hard code the MySQL connection string. But that is not a good practice. Because some configurations like the password will rapidly change. So if we hard code these settings, we need to compile the application each and every time after changing the password. So to avoid that overhead we use a configuration file called “App.Conf”. You can add this file to your project by going to add new item.

This is an XML file. So to add the MySQL connection string data, you need to modify this XML file into something like this.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>  
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="MySQLConStr" 
             connectionString="User Id=user; 
                               password=password; 
                               Persist Security Info=True; 
                               server=localhost; 
                               database=test"
             providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
</configuration>

Then go to your C# code and modify the connection string to something like this. To do this you may need to add a namespace,
using System.Configuration;

string ConString = ConfigurationManager.ConnectionStrings["MySQLConStr"].ToString();
Note: - Give the same name to both <add name="" ... > and ConnectionString[""].

No comments:

Post a Comment

Your comments are always welcome ...