I have a For Each loop written in Visual Basic that’s trying to modify a table it is iterating through. This is causing the “”Collection was modified; enumeration operation might not execute” exception.
What is frastrating about this is that I’ve tried to make copies of all the objects that I was using and and only removed from the copy but the exception still happened.
I know that this is due to my using a For Each loop instead of a For or While loop but I could not rewrite my code and make it work (I’m more familiar with C#). This is why I decided to ask for help here.
This is my code. How can I rewrite to be able to remove the Row that I wish to remove? Any help and code would be very appreciated!
Dim drAcademicRecord, drSchool As DataRow
For Each drSchool In dsR.Tables("School").Rows
If drSchool("OrganizationName") = "NA" Then
For Each drAcademicRecord In dsR.Tables("AcademicRecord").Rows
If drAcademicRecord("AcademicRecord_Id") = drSchool("AcademicRecord_Id") Then
dsR.Tables("AcademicRecord").Rows.Remove(drAcademicRecord) '<-- This is the line causing my exception
End If
Next
End If
Next
You don’t need to use
Because you have already got drAcademicRecord, so you can directly delete that row by
e.g.