delete loop

G

G. Dean Blake

When I do this.....

myDA.SelectCommand.Parameters("@SCID").Value = scid
Dim dt As New DataTable
myDA.Fill(dt)
If dt.Rows.Count > 0 Then
Dim myRow As DataRow = dt.Rows(0)
For Each myRow In dt.Rows
dt.Rows.Remove(myRow)
Next
End If

I get this exception....

Collection was modified; enumeration operation may not execute.


Why?
Thanks,
Dean
 
W

William Ryan eMVP

..Delete marks the row for deletion and I suspect that's what you want. It's
still in the collection until .AcceptChanges (or Update which calls
AcceptChanges) or RejectChanges is called.

Remove literally takes them out of the collection and is seldom what you
want to do b/c it guarantees that the removed rows will never be reflected
in the DB unless you do some extraordinary stuff to make sure it does.

Try .Delete instead of .Remove
That should do it for you , at a minimum it will fix this particular
problem.

HTH,

Bill

www.devbuzz.com
www.knowdotnet.com
 
M

Miha Markic [MVP C#]

Hi,

William explained you the details and I will explain you the error:
You can't remove items from collection within foreach loop.
If you really want to remove them, you should loop from dt.Rows.Count-1 to
0.
 
A

Andy Gaskell

And if you actually do want to remove the row you need create a For loop.

For i As Int32 = dt.Rows.Count - 1 To 0 Step -1
dt.Rows.Remove(dt.Rows(i))
Next
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top