我试图通过datagridview删除我的数据库中的记录,只需按下删除键,但它给我错误“索引超出范围。必须是非负数且小于集合的大小。”。这是我的代码
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
答案 0 :(得分:0)
我想知道问题出在“DataGridView1.Rows.Count - 1” 它可能没有执行-1计算...
尝试(DataGridView1.Rows.Count - 1)
答案 1 :(得分: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