Friday 10 August 2012

bind datagridview in c#

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:

No comments:

Post a Comment