我在 Form1 中有一个 GridView 和文本框。当 Form1 加载时,它会将数据从数据库加载到 Gridview 中。我有一个 Gridview 的 selectionChanged 事件,数据从那里进入文本框,现在我的问题是我想在文本框中编辑它们并将它们保存到数据库,但是当我单击保存按钮时,它会在数据库和 gridview 中创建一个新记录.如何解决这个问题?
下面是我的 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);
}
}
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");
正在插入一条新记录,因为您尝试更新的行的 RowState
属性设置为 Added
因为您要将单元格值分配给新行。您需要更新现有行的值。检查DbDataAdapter.Update Documentation :
When an application calls the Update method, the DbDataAdapter examines the RowState property, and executes the required INSERT, UPDATE, or DELETE statements iteratively for each row, based on the order of the indexes configured in the DataSet
试试这个:
private void btnSave_Click_1(object sender, EventArgs e)
{
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from Measurement where ID = @ID",con);
da.SelectCommand.Parameters.AddWithValue("@ID",int.Parse(txtID.Text));
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.Fill(ds, "Measurement");
if (String.IsNullOrEmpty(txtCellNo.Text.Trim()))
{
MessageBox.Show("Please enter Cell Number");
}
else
{
try
{
dr = ds.Tables["Measurement"].Rows[0];
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;
cb.GetUpdateCommand();
da.Update(ds, "Measurement");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
关于c# - 如何获取文本框,编辑它们并将它们保存回数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14727787/