Suppose I have a DataGridView called gridFiles.
For Each row as DataGridView in gridFiles.Rows
MsgBox(row.Cells("somekey").Value.ToString)
gridFiles.Rows.Remove(row)
Next
I will see message boxes, but only for every other row. What I think is happening is that the internal pointer for gridFiles.Rows gets off, because there is 1-fewer rows on the next iteration.
I need to iterate through every row, and conditionally decide whether to delete them or not (based on the success or failure of another action).
How can I get around this problem?
As you iterate through a collection
gridFiles.Rowsand remove from that collection you disturb the collection itself and iteration doesn’t work like it should (foreach attempts to get the next value, but the index has changed because of the item that has been removed) leaving you with an ‘every other’ evaluation.the solution (or A solution, there are other ways to skin this) is to put the items to be removed in there own collection and the after your foreach loop, loop through the ‘itemsToBeRemoved’ collection and remove those items from the original collection.