Error when deleting rows from DataTable : “There i

2019-06-02 02:03发布

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?

2条回答
地球回转人心会变
2楼-- · 2019-06-02 02:26

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
查看更多
We Are One
3楼-- · 2019-06-02 02:49

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
查看更多
登录 后发表回答