2014-11-14 62 views
2

我想通過datagridview更新數據庫,但我遇到的問題是,它只更新datagridview中的第一行。任何見解都將感激不盡,謝謝。更新命令只更新第一行vb.net

Dim Connection As New OleDbConnection(Get_Constring) 


    Dim dt As DataTable = New DataTable("SendTable") 
    Dim row As DataRow 
    dt.Columns.Add("ID", Type.GetType("System.Int32")) 
    dt.Columns.Add("Attendance", Type.GetType("System.String")) 
    For i = 0 To ClassRegisterdgv.Rows.Count - 1 
     ' If ClassRegisterdgv.Rows(i).Cells(4).Value.Equals("") Then ClassRegisterdgv.Rows(i).Cells(4).Value.Equals("Present") 
     Dim ID As Integer = ClassRegisterdgv.Rows(i).Cells(0).Value 
     Dim Attendance As String = ClassRegisterdgv.Rows(i).Cells(4).Value 
     row = dt.Rows.Add 
     row.Item("ID") = ID 
     row.Item("Attendance") = Attendance 
    Next 
    If Connection.State = ConnectionState.Closed Then 
     Connection.Open() 
    End If 
    Dim sqlquery As String = "UPDATE PupilInfo SET " & NewColumnCreated & " = @Attendance WHERE ID = @ID" 
    Dim sqlcommand As New OleDbCommand 

    For Each newrow As DataRow In dt.Rows 
     'For i = 0 To ClassRegisterdgv.Rows.Count - 1 
     With sqlcommand 
      .CommandText = sqlquery 
      .Parameters.AddWithValue("@Attendance", newrow.Item(1)) 
      .Parameters.AddWithValue("@ID", newrow.Item(0)) 
      .Connection = Connection 
      MessageBox.Show(newrow.Item(1) & newrow.Item(0)) 
      .ExecuteNonQuery() 

     End With 
    Next 

    Connection.Close() 
    ClassRegisterdgv.DataSource = Nothing 
    dt.Clear() 
+0

看起來像「.Add」邏輯對所有內容使用相同的「ID」?也許DIM在循環之外,然後在循環內設置值? – 2014-11-14 19:09:57

+0

@ WayneG.Dunn感謝您的幫助,但我設法修復它 – Jayy 2014-11-14 19:23:10

回答

2

只更新第一行,因爲命令對象的參數集合尚未清除。嘗試執行以下操作:

With sqlcommand 
    .CommandText = sqlquery 

    .Parameters.Clear() '<─────── Insert this line in your code. 

    .Parameters.AddWithValue("@Attendance", newrow.Item(1)) 
    .Parameters.AddWithValue("@ID", newrow.Item(0)) 
    .Connection = Connection 
    MessageBox.Show(newrow.Item(1) & newrow.Item(0)) 
    .ExecuteNonQuery() 
End With