Collection was modified; enumeration operation may not executehttp://forums.asp.net/t/1147145.aspx/1?Collection+was+modified+enumeration+operation+may+not+executeThu, 09 Dec 2010 15:44:56 -050011471451860980http://forums.asp.net/p/1147145/1860980.aspx/1?Collection+was+modified+enumeration+operation+may+not+executeCollection was modified; enumeration operation may not execute <p>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:&nbsp;<pre class="prettyprint">private void AddMenuContent(Control container, Menu menu, List&lt;Tab&gt; 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 &amp;&amp; menu.Id == t.Menu.Id &amp;&amp; !t.IsExcluded(currentSystemVersion) &amp;&amp; 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(&quot;&amp;lt;br /&gt;&quot;)); } } } // End foreach }</pre> </p> <p>This method is called from Page_Load of the User Control. Some times, this method throws this exception:</p> System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---&gt; System.InvalidOperationException: Collection was modified; enumeration operation may not execute.<br> &nbsp;&nbsp; at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)<br> &nbsp;&nbsp; at System.Collections.Generic.List`1.Enumerator.MoveNext() <p>Can anyone explain why this exception is being thrown? And why&nbsp;is it not thrown on every request?</p> <p>&nbsp;</p> 2007-08-16T10:37:01-04:001861100http://forums.asp.net/p/1147145/1861100.aspx/1?Re+Collection+was+modified+enumeration+operation+may+not+executeRe: Collection was modified; enumeration operation may not execute <p>Hi There,</p> <p>If you wish to add/edit/delete item from &lt;list&gt; best to use following to prevent modified enumeration collection.</p> <p>For ( int i = 0; i &lt; tabs.Count; i&#43;&#43; )</p> <p>{</p> <p>tabs[i] ......</p> <p>}</p> <p>Hope it helps!</p> 2007-08-16T11:49:21-04:001861127http://forums.asp.net/p/1147145/1861127.aspx/1?Re+Collection+was+modified+enumeration+operation+may+not+executeRe: Collection was modified; enumeration operation may not execute <p>But I'm not adding/editing/deleting any of the items&nbsp;in the <strong>tabs</strong> 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?</p> 2007-08-16T12:04:15-04:001861147http://forums.asp.net/p/1147145/1861147.aspx/1?Re+Collection+was+modified+enumeration+operation+may+not+executeRe: Collection was modified; enumeration operation may not execute <p>Hi There,</p> <p>What are you doing in this function ?</p> <p><span class="kwd"><font color="#0000ff">this</font></span>.AddTextElement(t, container, isActiveTab); // i doubt you are adding something to your tab ? if yes, is this editing?</p> <p>In addition of that, if you put the Foreach inside try and catch</p> <p>Try</p> <p>{</p> <p>foreach ....</p> <p>}</p> <p>catch</p> <p>{</p> <p>// do nothing</p> <p>}</p> <p>The operation will still complete and catches the error.</p> 2007-08-16T12:10:29-04:001861149http://forums.asp.net/p/1147145/1861149.aspx/1?Re+Collection+was+modified+enumeration+operation+may+not+executeRe: Collection was modified; enumeration operation may not execute <p>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.</p> 2007-08-16T12:12:46-04:001861164http://forums.asp.net/p/1147145/1861164.aspx/1?Re+Collection+was+modified+enumeration+operation+may+not+executeRe: Collection was modified; enumeration operation may not execute <p>Here is the code of the functions being called inside the foreach loop</p> <p>&nbsp;<pre class="prettyprint">private void AddImageElement(Tab t, Control c, bool isActiveTab) { Theme currTheme = SessionUtils.SessionContainer.Theme; string themePath = &quot;~/Themes/&quot; &#43; currTheme.Path &#43; &quot;/images/menu/&quot;; string languageExtension = &quot;en&quot;; if (_currentSystemLanguage != null) { languageExtension = _currentSystemLanguage.Culture; } string linkimage = &quot;&quot;; linkimage &#43;= @&quot;&amp;lt;img src=&quot;; if (isActiveTab) { linkimage &#43;= Page.ResolveUrl(themePath &#43; t.TabAlias &#43; &quot;.3.&quot; &#43; languageExtension &#43; &quot;.gif&quot;); } else { linkimage &#43;= Page.ResolveUrl(themePath &#43; t.TabAlias &#43; &quot;.1.&quot; &#43; languageExtension &#43; &quot;.gif&quot;); } linkimage &#43;= &quot; alt=\&quot;&quot; &#43; TabBLL.GetLocalizedTabTooltip(t) &#43; &quot;\&quot;&quot;; linkimage &#43;= &quot; border=\&quot;0\&quot;&amp;gt;&quot;; c.Controls.Add(new LiteralControl(&quot;&amp;lt;a href=\&quot;DesktopDefault.aspx?tabalias=&quot; &#43; t.TabAlias &#43; &quot;\&quot;&amp;gt;&quot; &#43; linkimage &#43; &quot;&amp;lt;/a&gt;&quot;)); } private void AddTextElement(Tab t, Control c, bool isActiveTab) { c.Controls.Add(new LiteralControl(&quot;&amp;lt;a href=\&quot;DesktopDefault.aspx?tabalias=&quot; &#43; t.TabAlias &#43; &quot;\&quot;&amp;gt;&quot; &#43; TabBLL.GetLocalizedTabName(t) &#43; &quot;&amp;lt;/a&gt;&quot;)); }</pre><pre class="prettyprint">As far as I can see, it is only the Control collection c that is being modified when new controls are added to it. But that's perfectly ok isn't it?</pre><pre class="prettyprint">Yes I can catch the exception, but I don't think that is very nice. I would rather know why it's telling me that the collection is being modified.</pre>&nbsp;</p> 2007-08-16T12:17:53-04:001861199http://forums.asp.net/p/1147145/1861199.aspx/1?Re+Collection+was+modified+enumeration+operation+may+not+executeRe: Collection was modified; enumeration operation may not execute <p>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 &quot;dirty&quot; 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?</p> 2007-08-16T12:34:03-04:003195610http://forums.asp.net/p/1147145/3195610.aspx/1?Re+Collection+was+modified+enumeration+operation+may+not+executeRe: Collection was modified; enumeration operation may not execute <p>[*-)]&nbsp;</p> 2009-05-29T08:07:51-04:004203915http://forums.asp.net/p/1147145/4203915.aspx/1?Re+Collection+was+modified+enumeration+operation+may+not+executeRe: Collection was modified; enumeration operation may not execute <p>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.</p> <p>It turns out that the problem came from a null item I&nbsp;was adding&nbsp;to the list. I wanted 1 item in the list, but didn't want it to contain any&nbsp;data.&nbsp;It&nbsp;didn't throw an exception when&nbsp;adding it. However, later when I tried to access the list it would give this exception.</p> <p><span style="font-family:; color:#808080"><span style="font-family:courier new,courier">System.InvalidOperationException&nbsp;- &quot;Collection was modified; enumeration operation may not execute.&quot;</span></span></p> <p>When I changed the code from this...</p> <p style="font-family:"><span style="font-family:courier new,courier"><span style="color:#808080">MyList.Add(null);</span></span></p> <p>To this...</p> <p><span style="font-family:; color:#808080"><span style="font-family:courier new,courier">MyList.Add(new MyListItem(param1, param2, ...));</span></span></p> <p>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.</p> 2010-12-09T15:44:56-05:00