Reputation: 77
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
Upvotes: 0
Views: 520
Reputation: 1128
You don't need to use
dsR.Tables("AcademicRecord").Rows.Remove(drAcademicRecord)
Because you have already got drAcademicRecord, so you can directly delete that row by
drAcademicRecord.Delete
e.g.
For Each drSchool As DataRow In dsR.Tables("School").Select("OrganizationName='NA'")
For Each drAcademicRecord As DataRow In dsR.Tables("AcademicRecord").Select("AcademicRecord_Id=" & drSchool("AcademicRecord_Id"))
drAcademicRecord.Delete
Next
Next
Upvotes: 1
Reputation: 78175
For i as integer = dsR.Tables("AcademicRecord").Rows.Count - 1 to 0 Step -1
If dsR.Tables("AcademicRecord").Rows(i)("AcademicRecord_Id") = drSchool("AcademicRecord_Id") Then
dsR.Tables("AcademicRecord").Rows.RemoveAt(i)
End If
Next
Upvotes: 3