Monday, 2 April 2012

How to Bind sql data to Datagridview in Windows application using C#.Net


Bind data to Datagridview in window application is same as bind data to Gridview in web application.
First Create one windows forms application give the name as Form.cs. In that form drag Datagridview from toolbox  and double click on form then form_load event will be opend in that write the following code:

private void Form1_Load(object sender, EventArgs e)
        {
            //This connection string is used to connect to database
            String strConnection = "Data Source=naresh;Initial Catalog=EMPDB;Integrated Security=True";
            //Establish SQL Connection
            SqlConnection con = new SqlConnection(strConnection);
            //Open database connection to connect to SQL Server
            con.Open();
            //Data table is used to bind the resultant data
            DataSet dsempdetails = new DataSet ();
            // Create a new data adapter based on the specified query.
            SqlDataAdapter da = new SqlDataAdapter("Select * from UserMaster", con);
            //SQl command builder is used to get data from database based on query
            SqlCommandBuilder cmd = new SqlCommandBuilder(da);
            //Fill data table
            da.Fill(dsempdetails,"EmpTable");
            //assigning data table to Datagridview
            dataGridView1.DataSource = dsempdetails .Tables[0];

            //Resize the Datagridview column to fit the gridview columns with data in datagridview
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            con.Close();
        }

After bind data to DataGridView then the output will be shown like this:


5 comments:

  1. Can you provide me Code For cascading datagridviewcomboboxcolumn in c#

    ReplyDelete
  2. I'm sorry but my I couldn't find method DataSource for DataGridView and AutoResizeColumns. They don't exist.

    ReplyDelete
  3. nice article can u tel me how to retrieve image from sql and display in datagrid??

    ReplyDelete