The code I have written below will do iteration of the loop properly. It tests the correct row against the condition, adds to the “secondary” DataTable and removes from the “master” as it is supposed to. However, upon the second iteration of the loop I get the following error:
Collection was modified; enumeration operation might not execute.
Here is the code I am using
For Each row As DataRow In tblAgencyEdInfo.Rows
Dim rDate As DateTime = row.Item("ExpirationDate")
If rDate < DateTime.Now Then
tblExpEdInfo.ImportRow(row)
tblAgencyEdInfo.Rows.Remove(row)
End If
Next row
You cannot modify a collection during enumeration. That means you cannot add or remove items. In this case you want to remove a DataRow from a DataTable in a
For Eachloop.The solution is either to
For-Loopand iterate the items backwards, removing the rows via index or toList(Of DataRow)) and add the matching rows you want to remove in theFor Each. Afterwards you just need to iterate this list and calltblAgencyEdInfo.Rows.Remove(rowToRemove)For example: