Page view counter

Collection was modified; enumeration operation may not execute

Last post 05-29-2009 4:07 AM by sirajulhasan. 7 replies.

Sort Posts:

  • Collection was modified; enumeration operation may not execute

    08-16-2007, 6:37 AM
    • Loading...
    • olanorm
    • Joined on 06-16-2005, 11:27 AM
    • Posts 30
    • Points 61

    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: 

    1    private void AddMenuContent(Control container, Menu menu, List<Tab> tabs, BasePageAdmin myPage)
    2    {
    3        Version currentSystemVersion = SessionUtils.SessionContainer.CurrentDepartment.Version;
    4        List currentUserRoles = SessionUtils.SessionContainer.User.Roles;
    5        
    6        foreach (Tab t in tabs)
    7        {
    8            // Only add tab to this menu if it is supposed
    9            // to be shown here, is in the current version and this user has access to it.
    10           if (t.Menu != null && menu.Id == t.Menu.Id && !t.IsExcluded(currentSystemVersion) && t.IsAuthorized(currentUserRoles))
    11           {
    12   
    13               // Mark as isActiveTab if this Tab is the currently displayed tab.
    14               bool isActiveTab = false;
    15               if (t.Id == myPage.ActiveTab.Id)
    16               {
    17                   isActiveTab = true;
    18               }
    19   
    20               // Decide what kind of menu to display
    21               switch (_menuType)
    22               {
    23                   case MenuTypes.Image:
    24                       this.AddImageElement(t, container, isActiveTab);
    25                       break;
    26                   case MenuTypes.Text:
    27                       this.AddTextElement(t, container, isActiveTab);
    28                       break;
    29                   default:
    30                       this.AddTextElement(t, container, isActiveTab);
    31                       break;
    32               }
    33   
    34               // Decide if we should display the menu as vertical or horizontal
    35               if (_orientation == Orientations.Vertical)
    36               {
    37                   MenuContent.Controls.Add(new LiteralControl("&lt;br />"));
    38               }
    39   
    40           }
    41       } // End foreach
    42   }
    43   
    

    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?

     

  • Re: Collection was modified; enumeration operation may not execute

    08-16-2007, 7:49 AM
    • Loading...
    • d4dennis@inspir3
    • Joined on 09-20-2006, 6:38 AM
    • Melbourne, Australia
    • Posts 1,302
    • Points 9,157

    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!

    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.
    Filed under:
  • Re: Collection was modified; enumeration operation may not execute

    08-16-2007, 8:04 AM
    • Loading...
    • olanorm
    • Joined on 06-16-2005, 11:27 AM
    • Posts 30
    • Points 61

    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?

  • Re: Collection was modified; enumeration operation may not execute

    08-16-2007, 8:10 AM
    • Loading...
    • d4dennis@inspir3
    • Joined on 09-20-2006, 6:38 AM
    • Melbourne, Australia
    • Posts 1,302
    • Points 9,157

    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.

    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.
  • Re: Collection was modified; enumeration operation may not execute

    08-16-2007, 8:12 AM
    • Loading...
    • valenumr
    • Joined on 12-31-2006, 1:27 PM
    • Posts 372
    • Points 2,035

    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.

  • Re: Collection was modified; enumeration operation may not execute

    08-16-2007, 8:17 AM
    • Loading...
    • olanorm
    • Joined on 06-16-2005, 11:27 AM
    • Posts 30
    • Points 61

    Here is the code of the functions being called inside the foreach loop

     

    1            private void AddImageElement(Tab t, Control c, bool isActiveTab)
    2            {
    3                Theme currTheme = SessionUtils.SessionContainer.Theme;
    4                string themePath = "~/Themes/" + currTheme.Path + "/images/menu/";
    5    
    6                string languageExtension = "en";
    7                if (_currentSystemLanguage != null)
    8                {
    9                    languageExtension = _currentSystemLanguage.Culture;
    10               }
    11   
    12               string linkimage = "";
    13               linkimage += @"&lt;img src=";
    14               if (isActiveTab)
    15               {
    16                   linkimage += Page.ResolveUrl(themePath + t.TabAlias + ".3." + languageExtension + ".gif");
    17               }
    18               else
    19               {
    20                   linkimage += Page.ResolveUrl(themePath + t.TabAlias + ".1." + languageExtension + ".gif");
    21               }
    22               linkimage += " alt=\"" + TabBLL.GetLocalizedTabTooltip(t) + "\"";
    23               linkimage += " border=\"0\"&gt;";
    24   
    25               c.Controls.Add(new LiteralControl("&lt;a href=\"DesktopDefault.aspx?tabalias=" + t.TabAlias + "\"&gt;" + linkimage + "&lt;/a>"));
    26           }
    27   
    28           private void AddTextElement(Tab t, Control c, bool isActiveTab)
    29           {
    30               c.Controls.Add(new LiteralControl("&lt;a href=\"DesktopDefault.aspx?tabalias=" + t.TabAlias + "\"&gt;" + TabBLL.GetLocalizedTabName(t) + "&lt;/a>"));
    31           }
    32   
    33   
    
    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?
    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.
     
  • Re: Collection was modified; enumeration operation may not execute

    08-16-2007, 8:34 AM
    Answer
    • Loading...
    • valenumr
    • Joined on 12-31-2006, 1:27 PM
    • Posts 372
    • Points 2,035

    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?

  • Re: Collection was modified; enumeration operation may not execute

    05-29-2009, 4:07 AM
    • Loading...
    • sirajulhasan
    • Joined on 05-27-2009, 2:25 AM
    • Posts 1
    • Points 2

    Confused 

Page 1 of 1 (8 items)