Deleting a datatable row while looping through it
I am using the code below to loop through the rows of a datatable. If a certain condition is met I then delete the row from the datatable.
This then causes a "System.InvalidOperationException: 'Collection was modified; enumeration operation might not execute.'" error.
What is the proper way to do this, so that the loop processes all rows? Thanks.
Code:
For Each row As DataRow In DT.Rows
'do some stuff here
If someCondition = True Then
DT.Rows.Remove(row)
End If
Next
Re: Deleting a datatable row while looping through it
I should think pass the datarows to a new datarow collection, delete the needed rows and rebind that collection, although to be fair I haven't used gridview for a while so maybe a better solution exists.
Re: Deleting a datatable row while looping through it
See here: https://stackoverflow.com/questions/...-for-each-loop
Quote:
You cannot delete an object from a collection during enumeration. You cannot modify the collection at all. That will cause an error (Collection was modified; enumeration operation may not execute).
If i have to change (especially delete) an item in a "List", i use the second approach in the SO-Link: Going backwards through the List
Re: Deleting a datatable row while looping through it
The other option that's not mentioned in that SO answer is to create a new list containing all the items first and enumerate that. That way, removing items from the original list will not affect the list being enumerated. This is the least efficient option but most lists will be relatively small and so it won;t really make a noticeable difference and the code will be more succinct. E.g.
Code:
For Each row As DataRow In DT.Rows.Cast(Of DataRow)().ToList()
'do some stuff here
If someCondition = True Then
DT.Rows.Remove(row)
End If
Next
Re: Deleting a datatable row while looping through it
Why do I have the impression that you can remove from a list with linq? And I have done so in the past...Hmmm....
Also this might be helpful: http://venkateswarlu.net/dot-net/rem...ist-using-linq