c#
  • windows-forms-designer
  • 2013-08-23 75 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();後再試

    相關問題