System.ArgumentOutOfRangeException 由于条目已从数据库中删除,在 For 循环中。帮忙修一下

System.ArgumentOutOfRangeException in For loop due to entry deleted from database. Help fix it

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim TimeNow As DateTime
    TimeNow = DateTime.Now
    With ReservationTableDataGridView
        For i As Integer = 0 To (.Rows.Count - 1)
            ListView1.BackColor = Color.Black
            Dim ToBeTested As DateTime
            ToBeTested = (.Rows(i).Cells(1).Value) #
            Console.WriteLine(ToBeTested)
            If ToBeTested > TimeNow.AddMinutes(45) Then
                Me.ReservationTableTableAdapter.Delete((.Rows(i).Cells(4).Value), (.Rows(i).Cells(1).Value), (.Rows(i).Cells(2).Value), (.Rows(i).Cells(3).Value))
                Me.ReservationTableTableAdapter.Fill(Me.CustomerResDataBaseDataSet.ReservationTable)
            End If
        Next
    End With
End Sub

我正在尝试编写一些代码,以便在设置的预订时间过去 45 分钟后从数据库中删除预订。我不断收到 System.ArgumentOutOfRangeException 错误。我相信这是因为它从数据库中删除一个项目后,它的值比索引少。谁能帮我解决这个问题?

这是收到的错误,{“索引超出范围。必须为非负数且小于集合的大小。 参数名称:index"}。我相信这是由于“#”行造成的。

尝试倒退 - For i As Integer = (.Rows.Count - 1) to 0 Step -1.

问题是您在尝试迭代时删除了 ReservationTableDataGridView 中的行,从而更改了索引。

通过倒退,您总是有一个有效的索引。