Error when deleting rows from DataTable : “There is no row at position X.”

北战南征 提交于 2019-12-08 04:55:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!