1

如何更新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;
}
4

2 回答 2

1

打电话dataGridView2.Update();cmd.ExecuteNonQuery();重试

于 2013-08-23T12:11:59.620 回答
1

好的,这就是你想要做的:

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语句。

于 2013-08-23T12:13:10.863 回答