I'm working on datagridview in c# windows forms application and I'm loading the data from the database, now i want the user to be able to able to edit the cell value and save the value to the database, how to edit the cell value and how can i save the value to the database?
SqlConnection con = new SqlConnection("user id=sa;password=123;database=employee");
SqlDataAdapter da = new SqlDataAdapter("select * from UserReg", con);
DataSet ds = new DataSet();
da.Fill(ds, "p");
dataGridView1.DataSource = ds.Tables["p"];
Try to do this:
One of the way to update a database with
DataGridView
is using of DataGridView's events:Let say:
private DataGridView dgv;
Add handlers of eventsI used OleDb but you can use SQL. Here is the code I usually use for the same.
Add this line of code to enable editing on datagridview
Then use below event
The above two events will enable editing in datagridview.
Then use below event to save the updated data back to db.
Have a look at the
DataGridView
Events list. You need to subscribe to the appropriate event, and handle it accordingly. Namely, you're interested inDataGridView.CellValueChanged
.