Posts
1150
Comments
891
Trackbacks
1
Collection was modified; enumeration operation may not execute. Why?

You can't modify a collection while iterating over it, so try this instead.

Where items is IList<T>, item is an Object T, and you want to remove based on the item's ItemID:

if (items != null)
            {
                for (int j = items.Count - 1; j >= 0; j--)
                {
                    if (items[j].ItemID == item.ItemID)
                    {
                        items.Remove(items[j]);
                    }
                }
            }

posted on Saturday, February 03, 2007 12:50 PM Print
Comments
Gravatar
# re: Collection was modified; enumeration operation may not execute. Why?
pavan
7/18/2008 12:59 AM
In the below code i have a webuser control (.ascx) with name cntl..if I loop inside controls of the user control im finding a textbox ,, if i find a text box with the specified name,i have to replace it with a dropdown list .. Im able to add textbox and add ddl.. but the problem is once i addd ddl when it reaches foreach loop then it throws an exception..

Exception details : Collection was modified; enumeration operation may not execute


foreach (Control ctrl in ctnl.Controls)
{

Type ctrlType = ctrl.GetType();

if (object.ReferenceEquals(ctrlType, typeof(TextBox)))

{

if (ctrl.ID.Substring(3) == (chk.ID.Substring(3)))

{

ddlBox = new DropDownList();

string str = "ddl" + chk.ID.Substring(3);

ddlBox.ID = str;

ddlBox.Items.Add("Hurix");

ddlBox.Items.Add("Hurix Learning");

ddlBox.Items.Add("Hurix Technology");

//ddlBox = (DropDownList)(ctnl.FindControl("ddl" + chk.ID.Substring(3)));

//ddlBox.Visible = true;

//ctrl.Visible = false;

ctnl.Controls.Remove(ctrl);

ctnl.Controls.Add(ddlBox);

}

}

}
Gravatar
# re: Collection was modified; enumeration operation may not execute. Why?
jdn
7/18/2008 8:34 AM
It's the same issue, you are trying to modify the enumeration (ctnl.Controls) while iterating over it. You need to find a way to add to it from the outside.
Gravatar
# mr
xbit
4/19/2011 8:23 PM
rather then using foreach use a simple for loop. You cant modify a enumrator in foreach loop.
Gravatar
# re: Collection was modified; enumeration operation may not execute. Why?
jdn
4/19/2011 9:06 PM
@xbit

That's what I said.

There are times when you don't want to use a for loop, so this is an alternative, but a foor loop is certainly a totally viable option.

Post Comment

Title *
Name *
Email
Url
Comment *  
Please add 3 and 1 and type the answer here: