How to update DataGridView into Databae c#.net

DataGridView:
  DataGridView control is the most important and high features and little tipycal control in C#.Net.The DataGridView control will be like a ecell datasheet. So if u want to use this control you have to maintain all the cells in the datasheet. Here the control having Rows and Columns. These rows and columns must maintain carefully.
            To update the DataGridView control with the DataAdapter is an easy thing. To do that you have to maintain some little steps here. Those this must be maintain some steps while writing the code, then only you will update the datagridview successfully to the database.


To Update the DataGridView the steps to follow are

*One of the column in the database must have PrimaryKey.
*Use commandbuilder
*Use Dataset and DataAdapter

Event: Write this code in form load.

SqlConnection cn = new SqlConnection(@"Data Source=CENSYS10\SQLEXPRESS;Integrated Security=true;Initial Catalog=master");
cn.Open();

SqlDataAdapter da = new SqlDataAdapter("select * from table", cn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Fill(ds, "new");


dataGridView1.DataSource = ds.Tables[0];

   With the code the data from database will display on datagridview. To update the modifications in the datagridview control Write the bellow code.

Event: Write the code in Update button click_event.

da.Update(ds, "new");
MessageBox.Show("Changes saved successfully");


I hope this code will solve your problem.

No comments:

Post a Comment