Link to home
Start Free TrialLog in
Avatar of lapucca
lapucca

asked on

Why am I getting an out of rang exception with the following "for loop"?

           int dropDownCount = actionMenu.DropDownItems.Count;
            if(dropDownCount > 6)
            {
                for (int index = 6; index < dropDownCount; index++)
                {
                    actionMenu.DropDownItems.RemoveAt(index);

                }
            }

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Expert1701
Expert1701

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Expert1701
Expert1701

Or even,

  while(actionMenu.DropDownItems.Count > 6)
    actionMenu.DropDownItems.RemoveAt(6);
Avatar of lapucca

ASKER

Nop, I was trying to remove all items after the 6th item.  I got it working now.  You see, the count is changing with each item I remove so it eventually ran out and got the exception error.  Thanks.
Avatar of Dmitry G
I believe the reason is that you alter underlying collection, and therefore alter the count of items.

Try to use 'while' loop:

while(actionMenu.DropDownItems.Count>6){
    actionMenu.DropDownItems.RemoveAt(6);
}