I have a menu and I am disabling certain options for certain group. It is dropdown menu with about 10 entriees. When I run code like this
menuMain.Items[0].ChildItems.RemoveAt(0);
menuMain.Items[0].ChildItems.RemoveAt(1);
menuMain.Items[0].ChildItems.RemoveAt(2);
menuMain.Items[0].ChildItems.RemoveAt(3);
menuMain.Items[0].ChildItems.RemoveAt(4);
menuMain.Items[0].ChildItems.RemoveAt(5);
which means I want to remove first 6 entries for this one group, I get exception at item no 5, saying the index is out of range.
I found the above code removes every other item from menu, not the one that are referenced.
removes 0th item
removes 2nd item
removes 4rd item
...
removes 10th item
removes 12th item (index not found)
Does anyone know why it is behaving like this?
Note: I checked the code in debug mode and it does points to correct menuitem that is both odd and even and it does not jump by 2.
Yes – imagine you initially have items
[a, b, c, d, e, f, g, h, i, j, k, l, m].Now you call
RemoveAt(0). That removes the first item (a), leaving you with[b, c, d, e, f, g, h, i, j, k, l, m].Now you call
RemoveAt(1). That removes the second remaining item (c), leaving you with[b, d, e, f, g, h, i, j, k, l, m].Now you call
RemoveAt(2). That removes the third remaining item (e), leaving you with:[b, d, f, g, h, i, j, k, l, m].… etc
The problem is that you’re thinking of the indexes in the original list – not after the “removals so far”. If you want to remove the first 6 entries, you can use: