Error when delete a row

  • Thread starter Thread starter Nguyen
  • Start date Start date
N

Nguyen

Do you know what's wrong with the code below? I get an error: error in
method ~MoveNext: collection was modified. Enumeration operation may not
execute. It happens when I step through the 'Next' of for-loop

Thanks in advance,

V.

-----------------------------------

Dim dtRow As DataRow

With ds.Tables(0)

For Each dtRow In .Rows

If dtRow.IsNull("POPLINE") Then

dtRow.Delete()

End If

Next

End With
 
Nguyen,

It's not allowed to change the iteration variable of a for each loop.
In this case 'dtRow'!
When you call dt.Row.Delete() you attempt to change this variable...

You can easily verify this beheaviour by typing this into your compiler:
(you can change it to VB...)

int[] intArray = {1, 2, 3, 4}; //Array of integers

foreach(int i in intArray)
{
i = 5;
}

The above code will not compile!!

I hope this helps...

Peter
 
Hi,

Your code will work only sometimes.
It will work on rows that are not added (when Deleting those rows, only
their RowStatus is changed) but it won't work on rows that are added
(Deleting those rows will remove them) because of nature of foreach.
Instead, do the inverse loop
Dim i as integer
For i = .Rows-1 to 0 step -1
...
next
 
Back
Top