I have a Page where I have placed a User Control. The User Control is responsible for dynamically showing a menu based on values in a database. The code for adding the menu looks like this:
private void AddMenuContent(Control container, Menu menu, List<Tab> tabs, BasePageAdmin myPage)
{
Version currentSystemVersion = SessionUtils.SessionContainer.CurrentDepartment.Version;
List currentUserRoles = SessionUtils.SessionContainer.User.Roles;
foreach (Tab t in tabs)
{
// Only add tab to this menu if it is supposed
// to be shown here, is in the current version and this user has access to it.
if (t.Menu != null && menu.Id == t.Menu.Id && !t.IsExcluded(currentSystemVersion) && t.IsAuthorized(currentUserRoles))
{
// Mark as isActiveTab if this Tab is the currently displayed tab.
bool isActiveTab = false;
if (t.Id == myPage.ActiveTab.Id)
{
isActiveTab = true;
}
// Decide what kind of menu to display
switch (_menuType)
{
case MenuTypes.Image:
this.AddImageElement(t, container, isActiveTab);
break;
case MenuTypes.Text:
this.AddTextElement(t, container, isActiveTab);
break;
default:
this.AddTextElement(t, container, isActiveTab);
break;
}
// Decide if we should display the menu as vertical or horizontal
if (_orientation == Orientations.Vertical)
{
MenuContent.Controls.Add(new LiteralControl("<br />"));
}
}
} // End foreach
}
This method is called from Page_Load of the User Control. Some times, this method throws this exception:
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNext()
Can anyone explain why this exception is being thrown? And why is it not thrown on every request?
If you wish to add/edit/delete item from <list> best to use following to prevent modified enumeration collection.
For ( int i = 0; i < tabs.Count; i++ )
{
tabs[i] ......
}
Hope it helps!
enumeration
DC517 Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved.
But I'm not adding/editing/deleting any of the items in the tabs collection inside the foreach loop? I'm only adding to the Control called container that I'm passing as a parameter. Or is it maybe that one that is causing the problem?
this.AddTextElement(t, container, isActiveTab); // i doubt you are adding something to your tab ? if yes, is this editing?
In addition of that, if you put the Foreach inside try and catch
Try
{
foreach ....
}
catch
{
// do nothing
}
The operation will still complete and catches the error.
DC517 Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved.
You can't add or remove items for a collection in a foreach loop. Try converting the collection to an array (use Collection.ToArray()), and iterate over the array. Then you can add items to the collection, since you are iterating over the array, not the
collection.
that does certainly seem to be the case (that you are only modifying Controls). So either there is some wierd reference foo (did you add the Tabs objects to the Control's collection?), or you are somehow modifying a tab indirectly. I *think* that most collections
have a "dirty" property for their items, and if that flag is set during an iteration, it freaks out.... anyhow, try the array thing I mentioned... it should work?
I was having this problem as well with the same exception you were getting. I saw the part about modifying the List object inside a foreach loop, but mine wasn't even inside a foreach loop.
It turns out that the problem came from a null item I was adding to the list. I wanted 1 item in the list, but didn't want it to contain any data. It didn't throw an exception when adding it. However, later when I tried to access the list it would give this
exception.
System.InvalidOperationException - "Collection was modified; enumeration operation may not execute."
When I changed the code from this...
MyList.Add(null);
To this...
MyList.Add(new MyListItem(param1, param2, ...));
It worked just fine; no more exception! I don't know if this applies to other people's instances of getting this exception, but I hope it helps.
Nathon Dalton
http://nathondalton.wordpress.com
Software Developer
Systems Administrator
Network Administrator
olanorm
Member
61 Points
30 Posts
Collection was modified; enumeration operation may not execute
Aug 16, 2007 10:37 AM|LINK
I have a Page where I have placed a User Control. The User Control is responsible for dynamically showing a menu based on values in a database. The code for adding the menu looks like this:
private void AddMenuContent(Control container, Menu menu, List<Tab> tabs, BasePageAdmin myPage) { Version currentSystemVersion = SessionUtils.SessionContainer.CurrentDepartment.Version; List currentUserRoles = SessionUtils.SessionContainer.User.Roles; foreach (Tab t in tabs) { // Only add tab to this menu if it is supposed // to be shown here, is in the current version and this user has access to it. if (t.Menu != null && menu.Id == t.Menu.Id && !t.IsExcluded(currentSystemVersion) && t.IsAuthorized(currentUserRoles)) { // Mark as isActiveTab if this Tab is the currently displayed tab. bool isActiveTab = false; if (t.Id == myPage.ActiveTab.Id) { isActiveTab = true; } // Decide what kind of menu to display switch (_menuType) { case MenuTypes.Image: this.AddImageElement(t, container, isActiveTab); break; case MenuTypes.Text: this.AddTextElement(t, container, isActiveTab); break; default: this.AddTextElement(t, container, isActiveTab); break; } // Decide if we should display the menu as vertical or horizontal if (_orientation == Orientations.Vertical) { MenuContent.Controls.Add(new LiteralControl("<br />")); } } } // End foreach }This method is called from Page_Load of the User Control. Some times, this method throws this exception:
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidOperationException: Collection was modified; enumeration operation may not execute.at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNext()
Can anyone explain why this exception is being thrown? And why is it not thrown on every request?
d4dennis@ins...
Star
9229 Points
1314 Posts
Re: Collection was modified; enumeration operation may not execute
Aug 16, 2007 11:49 AM|LINK
Hi There,
If you wish to add/edit/delete item from <list> best to use following to prevent modified enumeration collection.
For ( int i = 0; i < tabs.Count; i++ )
{
tabs[i] ......
}
Hope it helps!
enumeration
Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved.
olanorm
Member
61 Points
30 Posts
Re: Collection was modified; enumeration operation may not execute
Aug 16, 2007 12:04 PM|LINK
But I'm not adding/editing/deleting any of the items in the tabs collection inside the foreach loop? I'm only adding to the Control called container that I'm passing as a parameter. Or is it maybe that one that is causing the problem?
d4dennis@ins...
Star
9229 Points
1314 Posts
Re: Collection was modified; enumeration operation may not execute
Aug 16, 2007 12:10 PM|LINK
Hi There,
What are you doing in this function ?
this.AddTextElement(t, container, isActiveTab); // i doubt you are adding something to your tab ? if yes, is this editing?
In addition of that, if you put the Foreach inside try and catch
Try
{
foreach ....
}
catch
{
// do nothing
}
The operation will still complete and catches the error.
Don't forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved.
valenumr
Contributor
2035 Points
372 Posts
Re: Collection was modified; enumeration operation may not execute
Aug 16, 2007 12:12 PM|LINK
You can't add or remove items for a collection in a foreach loop. Try converting the collection to an array (use Collection.ToArray()), and iterate over the array. Then you can add items to the collection, since you are iterating over the array, not the collection.
olanorm
Member
61 Points
30 Posts
Re: Collection was modified; enumeration operation may not execute
Aug 16, 2007 12:17 PM|LINK
Here is the code of the functions being called inside the foreach loop
private void AddImageElement(Tab t, Control c, bool isActiveTab) { Theme currTheme = SessionUtils.SessionContainer.Theme; string themePath = "~/Themes/" + currTheme.Path + "/images/menu/"; string languageExtension = "en"; if (_currentSystemLanguage != null) { languageExtension = _currentSystemLanguage.Culture; } string linkimage = ""; linkimage += @"<img src="; if (isActiveTab) { linkimage += Page.ResolveUrl(themePath + t.TabAlias + ".3." + languageExtension + ".gif"); } else { linkimage += Page.ResolveUrl(themePath + t.TabAlias + ".1." + languageExtension + ".gif"); } linkimage += " alt=\"" + TabBLL.GetLocalizedTabTooltip(t) + "\""; linkimage += " border=\"0\">"; c.Controls.Add(new LiteralControl("<a href=\"DesktopDefault.aspx?tabalias=" + t.TabAlias + "\">" + linkimage + "</a>")); } private void AddTextElement(Tab t, Control c, bool isActiveTab) { c.Controls.Add(new LiteralControl("<a href=\"DesktopDefault.aspx?tabalias=" + t.TabAlias + "\">" + TabBLL.GetLocalizedTabName(t) + "</a>")); }valenumr
Contributor
2035 Points
372 Posts
Re: Collection was modified; enumeration operation may not execute
Aug 16, 2007 12:34 PM|LINK
that does certainly seem to be the case (that you are only modifying Controls). So either there is some wierd reference foo (did you add the Tabs objects to the Control's collection?), or you are somehow modifying a tab indirectly. I *think* that most collections have a "dirty" property for their items, and if that flag is set during an iteration, it freaks out.... anyhow, try the array thing I mentioned... it should work?
sirajulhasan
Member
2 Points
1 Post
Re: Collection was modified; enumeration operation may not execute
May 29, 2009 08:07 AM|LINK
[*-)]
nathon
Member
80 Points
125 Posts
Re: Collection was modified; enumeration operation may not execute
Dec 09, 2010 03:44 PM|LINK
I was having this problem as well with the same exception you were getting. I saw the part about modifying the List object inside a foreach loop, but mine wasn't even inside a foreach loop.
It turns out that the problem came from a null item I was adding to the list. I wanted 1 item in the list, but didn't want it to contain any data. It didn't throw an exception when adding it. However, later when I tried to access the list it would give this exception.
System.InvalidOperationException - "Collection was modified; enumeration operation may not execute."
When I changed the code from this...
MyList.Add(null);
To this...
MyList.Add(new MyListItem(param1, param2, ...));
It worked just fine; no more exception! I don't know if this applies to other people's instances of getting this exception, but I hope it helps.
Nathon Dalton
http://nathondalton.wordpress.com
Software Developer
Systems Administrator
Network Administrator