Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
When i removing child item of menu1 .It is giving array out of bound why ?

VB
If user_type = "User" Then
            For i As Integer = 0 To Menu1.Items.Count - 1
                If (Menu1.Items(i).Text = "Master") Then
                    For j As Integer = 0 To Menu1.Items(i).ChildItems.Count - 1
                        If (Menu1.Items(i).ChildItems(j).Text = "Grade Detail") Then
                            'Menu1.Items(i).ChildItems(j).Selectable = False
                            Menu1.Items(i).ChildItems(j).Enabled = False
                            'Menu1.Items.RemoveAt(i)

                        End If
                        If (Menu1.Items(i).ChildItems(j).Text = "Machine Detail") Then
                            Menu1.Items(i).ChildItems(j).Enabled = False
                        End If
                        If (Menu1.Items(i).ChildItems(j).Text = "Customer Detail") Then
                            Menu1.Items(i).ChildItems(j).Enabled = False
                        End If
                        If (Menu1.Items(i).ChildItems(j).Text = "Max Rebar Per Cycle") Then
                            Menu1.Items(i).ChildItems(j).Enabled = False
                        End If
                        If (Menu1.Items(i).ChildItems(j).Text = "Plant Capacity") Then
                            Menu1.Items(i).ChildItems(j).Enabled = False
                        End If
                    Next
                End If
            Next
        End If
Posted
Updated 10-Jul-12 17:35pm
v2

1 solution

The problem is very simple, it is visible from the first glance. Consider some simplified code:

VB
For j As Integer = 0 To Menu1.Items(i).ChildItems.Count - 1 'incorrect, Count changes when you delete inside the loop
    If (someCondition) Then
       Menu1.Items.RemoveAt(i) 'incorrect: index is shifted as a result of previous deletion
    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
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900