我在 Form1 中有一个网格视图和文本框。当 Form1 加载时,它会将数据从数据库加载到 Gridview 中。我有一个 Gridview 的 selectionChanged 事件,数据从哪里进入文本框,现在我的问题是我想在文本框中编辑它们并将它们保存到数据库,但是当我点击保存按钮时,它正在数据库和 gridview 中创建一条新记录. 如何解决这个问题?
下面是我保存按钮的代码:
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);
}
}
网格视图的代码:
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();
}
}
}