如何更新DataGridView
使其也将影响数据库的更改?我正在尝试的代码是:
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
+ "'";
myCmd = "Update Details set Description = '"
+ myDgrow.Cells["Description"].Value
+ "', DateStarted='"
+ myDgrow.Cells["DateStarted"].Value
+ "',TeamSize='"
+ myDgrow.Cells["TeamSize"].Value
+ "',Manager='"
+ myDgrow.Cells["Manager"].Value
+ "' where ProjectName='"
+ myDgrow.Cells["ProjectName"].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;
dataGridView2.Update();
//cmd.Parameters.Clear();
cmd.ExecuteNonQuery();
myCmd = string.Empty;
}
好的,这就是您要执行的操作:
using (SqlConnection c = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, c))
{
cmd.Parameters.AddWithValue("@field1", myDgrow.Cells["field1"].Value);
...
cmd.ExecuteNonQuery();
}
其中sql
可能看起来是这样的:
UPDATE table SET field1 = @field1, field2 = @field2 WHERE fieldId = @fieldId
并且您将在foreach
循环中的每次迭代中执行此操作。
老实说,我不知道您在代码中正在做什么,因为您将myCmd
背对背设置为两个不同的东西,然后又没有使用它。所以我不知道该cmd
对象具有什么SQL 。因此,只需修改您的代码以使用我提出的结构,它便会按预期工作。
注意:我不知道是否允许用户添加到数据网格,但是如果允许,您将构建一个不同的表,sql
因为它需要是一条INSERT
语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句