Datagridview Updating

China☆狼群 提交于 2019-12-06 13:55:16

问题


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;
}

回答1:


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();
}

where sql might look something like:

UPDATE table SET field1 = @field1, field2 = @field2 WHERE fieldId = @fieldId

and you're going to do that for each iteration inside the foreach loop.

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.

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.




回答2:


call dataGridView2.Update(); after cmd.ExecuteNonQuery(); and try again



来源:https://stackoverflow.com/questions/18402363/datagridview-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!