Frank
Frank

Reputation: 2045

For Each Loop error: Collection was modified; enumeration operation might not execute

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?

Upvotes: 0

Views: 3489

Answers (2)

bobbymcr
bobbymcr

Reputation: 24167

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:

Dim rowCount As Integer = dt.Rows.Count  ' Set upper bound = original row count
Dim index as Integer
For index = 0 To rowCount - 1  ' Iterate through the original set of rows
    Dim dRow as DataRow = dt.Rows.Item(index)  ' Get row by index
    dt.Rows.Add(dRow("CustNum"), dRow("SalesRepName"), dRow("mgrid"), "=""" & dRow("midValue") & """", dRow("dba"), dRow("sysDate"), dRow("statusID"))
Next index

Upvotes: 2

Ry-
Ry-

Reputation: 225124

You're adding items to a collection you're enumerating. Logically, it would loop infinitely. This sort of situation can't occur. If you really mean to do that, split it in two by creating a Structure or Class for your data, adding the items to a list, then looping through the list and adding the items to the table.

Upvotes: 2

Related Questions