I am encountering an error when looping through datarows. I searched SO and tried the solutions, but no luck.
Collection was modified; enumeration operation might not execute.
Dim dRow As DataRow
For Each dRow In dt.Rows
dt.Rows.Add(dRow("CustNum"), dRow("SalesRepName"), dRow("mgrid"), "=""" & dRow("midValue") & """", dRow("dba"), dRow("sysDate"), dRow("statusID"))
Next
The error occurs the first time the code hits “Next“
What would be causing Collection was modified; enumeration operation might not execute.How can I resolve this error?
You cannot enumerate a collection while updating it. Even if this code actually did work, it would run forever because you keep adding more and more rows and it would keep enumerating them.
You can change your approach slightly and make this work by using a for loop with an index counter and a fixed upper bound.
Something like this should work: