0

我试图通过datagridview删除我的数据库中的一条记录,只需按下delete键,但它给我错误“索引超出范围。必须是非负数并且小于集合的大小。”。这是我的代码

Private Sub DataGridView1_UserDeletedRow(sender As Object, e As DataGridViewRowEventArgs) Handles DataGridView1.UserDeletedRow

    For i = 0 To DataGridView1.Rows.Count - 1

        Dim deleterows As Integer = DataGridView1.SelectedRows(i).Cells(0).Value
        Dim sqlquery As String = "delete from tblname where ID = " & deleterows & ";"
        Dim sqlcommand As New OleDbCommand

        With sqlcommand
            .CommandText = sqlquery
            .Connection = conn
            .ExecuteNonQuery()
        End With

    Next

End Sub
4

2 回答 2

0

如果您想使用循环删除行,请尝试向后遍历您的行(即从最后一行开始并向后工作,而不是从前面开始并向前工作)。

对于您所描述的内容,将循环全部放在一起(使用您自己的代码)可能会更好:

 Dim deleterows As Integer = DataGridView1.SelectedRows(i).Cells(0).Value
 Dim sqlquery As String = "delete from tblname where ID = " & deleterows & ";"
 Dim sqlcommand As New OleDbCommand

 With sqlcommand
     .CommandText = sqlquery
     .Connection = conn
     .ExecuteNonQuery()
 End With
于 2013-11-12T16:15:21.613 回答
0

我想知道问题是否出在“DataGridView1.Rows.Count - 1”上,它可能没有执行 -1 计算......

尝试(DataGridView1.Rows.Count - 1)

于 2013-11-12T14:50:57.893 回答