I have a gridview and Textboxes in Form1. When Form1 loads it will load the data into Gridview from database. I have a selectionChanged event of Gridview from where the data goes into textboxes and Now my problem is I want to edit them in Textboxes and save them to database, but When I click on save button it is creating a new record in the database and gridview. How to fix this ?
Below is my code for SaveButton:
private void btnSave_Click_1(object sender, EventArgs e)
{
DataRow dr = dt.NewRow();
da = new SqlDataAdapter("select * from Measurement", con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
dr["CellNumber"] = txtCellNo.Text.Trim();
dr["FirstName"] = txtFirstName.Text;
dr["LastName"] = txtLastName.Text;
dr["Shirt"] = txtShirt.Text;
dr["Pant"] = txtPant.Text;
dr["DueDate"] = txtDueDate.Text;
dr["Date"] = txtDate.Text;
if (dr["CellNumber"] == "")
{
MessageBox.Show("Please enter Cell Number");
}
else if (dr["CellNumber"] != "")
{
dr = dt.Select(" ID = " + txtID.Text)[0]; //updated here
}
try
{
da.Update(ds, "Measurement");
}
catch (DBConcurrencyException ex)
{
MessageBox.Show(ex.Message);
}
}
Code for Gridview:
private void dgv_SelectionChanged_1(object sender, EventArgs e)
{
if (dgv.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in dgv.SelectedRows)
{
//Send the first cell value into textbox'
txtLastName.Text = row.Cells["LastName"].Value.ToString();
txtFirstName.Text = row.Cells["FirstName"].Value.ToString();
txtCellNo.Text = row.Cells["CellNumber"].Value.ToString();
txtDate.Text = row.Cells["Date"].Value.ToString();
txtDueDate.Text = row.Cells["DueDate"].Value.ToString();
txtPant.Text = row.Cells["Pant"].Value.ToString();
txtShirt.Text = row.Cells["Shirt"].Value.ToString();
txtID.Text = row.Cells["ID"].Value.ToString();
}
}
}
da.Update(ds, "Measurement");is inserting a new record because theRowStateproperty of the row you are attempting to update is set toAddedsince you are assigning the cell values to a new row. You need to update the values of an existing row. Check DbDataAdapter.Update Documentation :Try this :