Re: For vs. For Each

From: David (dfoster_at_woofix.local.dom)
Date: 08/13/04


Date: Fri, 13 Aug 2004 13:36:52 -0700

On 2004-08-13, Alvin Bruney [MVP] <> wrote:
>
> Collection was modified; enumeration operation may not execute.
> Description: An unhandled exception occurred during the execution of the
> current web request. Please review the stack trace for more information
> about the error and where it originated in the code.
>
> Exception Details: System.InvalidOperationException: Collection was
> modified; enumeration operation may not execute.
>
> Source Error:
>
>
> Line 50: private void Button2_Click(object sender, System.EventArgs e)
> Line 51: {
> Line 52: foreach(ListItem li in ListBox1.Items)
> Line 53: ListBox1.Items.Remove(li);
> Line 54: }

Now, with all that in mind, let's go back a couple of posts and look at
the code I actually posted....

>>>For each item as Object In New ArrayList(ListBox1.SelectedItems)

You're iterating over the original collection, I am not. Now, I read
this in the VB.Net group so I just posted as VB, so I apologize if the
translation to C# threw you off, it's hard to know which group people
are posting from.

Try...

foreach(Object o in new ArrayList(ListBox1.SelectedItems))
{
        ListBox1.Items.Remove(o);
}

> running your code with a multiselect as opposed to one selection which i
> suspect you didn't do.

No, you either had trouble converting the code or just didn't read it
closely enough, I'm not sure which. Anyway, now that you see the
correct code hopefully my comments will make a little more sense to you.