【发布时间】:2013-08-27 07:24:38
【问题描述】:
当我使用以下代码时,循环会迭代两次,并且我收到错误消息,因为“变量名称 '@projectName1' 已被声明。变量名称在查询批处理或存储过程中必须是唯一的。”并在 datagridview 和表中重置表的所有值。实际上我想通过选择单元格来更新表单本身中的 DataGridView,它也应该在数据库中反映相同的内容。
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());
}
}
【问题讨论】:
-
你到底为什么要使用字符串连接值来构建命令,然后将值添加为在任何地方都不使用的参数?
-
好吧,你说我应该只用一个。谢谢,让我试试那个。
-
是的 - 与您上周提出的这个完全相同的问题的答案示例类似:stackoverflow.com/a/18402568