By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,947 Members | 1,594 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,947 IT Pros & Developers. It's quick & easy.

delete loop

P: n/a
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
Nov 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Hi Dean:

The foreach statement uses an Enumerator, which is a little object
optimized to move through a collection which doesn't change. The
enumerator carries a little bit of "state" about the collection it is
moving through. If the collection changes the state is invalid and the
enumerator doesn't know what the "right thing to do" is - it's pretty
dumb :)

Think of it as a way to avoid subtle problems like this:

string[] names = { "Tim", "Tim", "Gil" };
ArrayList nameList = new ArrayList( names );

for(int i = 0; i < nameList.Count; i++)
{
if((string)nameList[i] == "Tim")
{
nameList.Remove(nameList[i]);
}
}

The code above intends to remove all the "Tim" strings from the
collection but it doesn't. It will skip right over the second "Tim"
entry because the collection was modified and the state (i) could not
account for it.

One way I could write this to work would be like:

for(int i = nameList.Count - 1; i >= 0; i--)
{
if((string)nameList[i] == "Tim")
{
nameList.Remove(nameList[i]);
}
}

HTH,

--
Scott
http://www.OdeToCode.com

On Sat, 15 May 2004 09:34:40 -0700, "G. Dean Blake" <De**@nospam.com>
wrote:
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


Nov 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.