问题
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 ican even assume this value, since I'm looping from dt.Rows.Count -1.
Any idea what am I doing wrong here?
回答1:
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:
For Each num As Integer In numsArray
For i As Integer = dt.Rows.Count -1 To 0 Step -1
If dt.Rows(i).Item("number") = num Then
dt.Rows(i).Delete()
Exit For
End If
Next
Next
回答2:
The problem is that you are deleting rows and you are continuing with the bucle:
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()
Exit For ' You need to stop looking for a number in this row
End If
Next
Next
来源:https://stackoverflow.com/questions/19927672/error-when-deleting-rows-from-datatable-there-is-no-row-at-position-x