The problem is very simple, it is visible from the first glance. Consider some simplified code:
For j As Integer = 0 To Menu1.Items(i).ChildItems.Count - 1
If (someCondition) Then
Menu1.Items.RemoveAt(i)
End If
Next
Are you getting the idea? One possible and simple work-around is: 1) assign
Count
to some variable initialized before the loop, use this variable in the condition of the loop end instead of
Menu1.Items(i).ChildItems.Count
; this way, the loop end condition will depend on a value which is not modified in the cycle (so called
cycle invariant); 2) execute the loop in reverse, from
count - 1
down to
0
; this will eliminate the problem of shifting the item indices as a result of item removal.
Yes, this simple.
—SA