数据网格视图更新 [英] Datagridview Updating
问题描述
如何更新 DataGridView
以便它也影响数据库中的更改?我正在尝试的代码是:
How to update the DataGridView
so that it will effect the changes in database too?
The code which I am trying is:
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;
}
推荐答案
好的,这就是你想要做的:
Okay, so this is what you want to do:
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
循环内的每次迭代执行此操作.
and you're going to do that for each iteration inside the foreach
loop.
老实说,我不知道您在代码中做什么,因为您将 myCmd
设置为两个不同的东西,然后您就没有使用它.所以我不知道 cmd
对象有什么 SQL.因此,只需修改您的代码以使用我提出的结构,它就会按预期工作.
I honestly don't know what you're doing in your code because you're setting myCmd
, back to back, to two different things, and then you're not using it. So I have no idea what SQL the cmd
object has. So just modify your code to use the structure I put forth and it will work just as expected.
注意:我不知道是否允许用户添加到数据网格,但如果允许,您将构建一个不同的 sql
因为它将需要是一个 INSERT
语句.
NOTE: I don't know if the users are allowed to add to the data grid, but if they are, you'll build a different sql
because it will need to be an INSERT
statement.
这篇关于数据网格视图更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!