当我使用以下代码时,循环迭代两次,并且收到错误消息:“变量名‘@projectName1’已被声明。变量名在查询批处理或存储过程中必须是唯一的。”并重置 datagridview 和表中表的所有值。实际上,我想通过选择单元格来更新表单本身中的 DataGridView,它也应该在数据库中反射(reflect)相同的情况。
private void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = Helper.getconnection();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string myCmd = string.Empty;
foreach (DataGridViewRow myDgrow in dataGridView2.Rows)
{
myCmd = "Update Details set ProjectName='" + myDgrow.Cells["ProjectName"].Value + "', Description = '" + myDgrow.Cells["Description"].Value + "', DateStarted='" + myDgrow.Cells["DateStarted"].Value + "',TeamSize='" + myDgrow.Cells["TeamSize"].Value + "',Manager='" + myDgrow.Cells["Manager"].Value + "'";
cmd.Parameters.AddWithValue("@projectName1", myDgrow.Cells["ProjectName"].Value);
cmd.Parameters.AddWithValue("@Description1", myDgrow.Cells["Description"].Value);
cmd.Parameters.AddWithValue("@DateStarted1", myDgrow.Cells["DateStarted"].Value);
cmd.Parameters.AddWithValue("@TeamSize1", myDgrow.Cells["TeamSize"].Value);
cmd.Parameters.AddWithValue("@Manager1", myDgrow.Cells["Manager"].Value);
cmd.CommandText = myCmd;
cmd.ExecuteNonQuery();
dataGridView2.Update();
myCmd = string.Empty;
}
DataTable details = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
try
{
da.Update(details);
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
最佳答案
您正在使用 foreach 循环并每次将参数添加到同一命令中。每次在循环中迭代时清除参数或每次创建一个新命令..
关于c# - DataGridView 更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18459416/