更新命令仅更新第一行vb.net

时间:2014-11-14 18:40:01

标签: database vb.net ms-access datagridview access-vba

我正在尝试通过datagridview更新数据库,但我遇到的问题是它只更新了datagridview中的第一行。任何见解都会感激不尽,谢谢。

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

1 个答案:

答案 0 :(得分: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