Every other row hit during For Each on DataGridViewRow with Remove
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, b开发者_开发技巧ut 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?
dim deleteList As new List(Of DataGridViewRow)
For Each row as DataGridViewRow in gridFiles.Rows
MsgBox(row.Cells("somekey").Value.ToString)
deleteList.Add(row)
Next
For Each row As DataGridViewRow in deleteList
gridFiles.Rows.Remove(row)
Next
Or, itterate the collection backwards
For i As Integer = gridFiles.Rows.Count - 1 To 0 Step -1
MsgBox(row.Cells("somekey").Value.ToString)
gridFiles.Rows.Remove(gridFiles.Rows(i))
End If
As you iterate through a collection gridFiles.Rows
and 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.
精彩评论