Monday 2 April 2012

Loading Record to Datagridview from sql server tables in c#...

Open a new Windows Project.....
 Open Form1.cs Design...
 Add a Datagriview from Toolbox...
 add a Button named LoadTable,
 Double Click on Button LoadTable, it will direct to form1.cs ...
...
...
private void button1_Click(object sender, EventArgs e)
        {

        }

Then,
Right click on Namespace in Solution Explorer,
then click, add  new item  Application Configuration File, 

then type the below code, to connect to sqlserver database.

...
...
 <connectionstrings>
    <add connectionstring="Data source=.;database=MassMail;Integrated Security=true;Initial Catalog=MassMail" name="sql" providername="System.Data.SqlClient">
  </add></connectionstrings>
...
...

here connection string name is "sql"
database name is "massmail"
server name is "." it means choosing default server...

To Connect to sql server, Right click on Namespace in Solution Explorer, then click add  new item Class named Common.
Type the Below Code,

...
...
class Common
    {
        public static SqlConnection GetConnection()
        {
            SqlConnection sqlcon = new SqlConnection();
            string constr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            sqlcon.ConnectionString = constr;
            return sqlcon;
        }
    }
...
...

Then type the below code in Form1.cs 

Right click on Namespace in Solution Explorer, the click add Reference, then add system.configuration,
After that,

using System.Windows.Forms;
using System.Data.SqlClient;
...
...
private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection sqlcon = Common.GetConnection();
            sqlcon.Open();
            SqlCommand sqlcmd = new SqlCommand("Select * from ContactsTable", sqlcon);
            SqlDataAdapter sqlda=new SqlDataAdapter(sqlcmd);
            DataSet ds=new DataSet();
            sqlda.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];       
               
        }
}

then Compile and run...


No comments:

Post a Comment