c#
  • windows-forms-designer
  • 2013-08-23 76 views 1 likes 
    1

    如何更新DataGridView以便它也会影响数据库中的更改? 我正努力的代码是: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; 
    } 
    
    +0

    call dataGridView2.Update();在cmd.ExecuteNonQuery()之后;并重试 – Sumeshk

    +0

    [DataGridView更新数据库]的可能重复(http://stackoverflow.com/questions/18459416/datagridview-updating-database) – Bridge

    回答

    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,背靠背,两个不同的东西,然后你不使用它。所以我不知道对象具有什么SQL。所以只要修改你的代码来使用我提出的结构,它就会像预期的那样工作。

    注:我不知道是否允许用户添加到数据网格,但如果是这样,您将构建一个不同sql,因为这将需要一个INSERT声明。

    1

    通话dataGridView2.Update();cmd.ExecuteNonQuery();后再试

    相关问题