I'm getting the following runtime error when trying to delete rows from a datatable dt
:
There is no row at position 24.
There is no row at position 20.
Here's the code (line 3 causes the error):
For i As Integer = dt.Rows.Count -1 To 0 Step -1
For Each num As Integer In numsArray
--> If dt.Rows(i).Item("number") = num Then
dt.Rows(i).Delete()
End If
Next
Next
Using a Try-Catch
block I found that whenever the error occurs the value of index variable i
equals dt.Rows.Count
, which is probably the reason for the error. However, it's unclear to me how i
can even assume this value, since I'm looping from dt.Rows.Count
-1
.
Any idea what am I doing wrong here?
The problem is that you are deleting rows and you are continuing with the bucle:
You're iterating over a row collection that you're deleting from; its like sawing through a ladder that you're standing on.
Try this code: