views:

64

answers:

3

I know it most likely possible to access a winforms menu like an array but I am not seeing it in the menu designer of VS2008? What I mean is, my app has a typical menu bar across the top, with multiple items on each drop down. As it is written (I inherited this code), each menu item is a separate name, i.e.

myMenuOption1MenuItem
myMenuOption2MenuItem
myMenuOption3MenuItem
myMenuOption4MenuItem

etc...

I need the ability to enable or disable (or even hide/unhide) menu options depending on user privileges, for example:

For I = 0 to maxIndex
    myMenuOption(I).Enabled = myUser.IsAdministrator
Next

Obviously I could set/unset each menu item by name, but for a lot of reasons I'd prefer to use loops.

+1  A: 

Each child menu item is in the DropDownItems collection - So you can loop through that (If you are using ToolStripMenuItems and not the older style menus).

Brody
+2  A: 

ToolStripMenuItems are exposed through ContextMenuStrip.Items

For Each myItem As ToolStripMenuItem In myContextMenuStrip.Items
    myItem.Enabled = myUser.IsAdministrator
Next
Factor Mystic
A: 

For Each Menu As ToolStripMenuItem In MenuPrincipal.Items

            For Each Item As ToolStripItem In Menu.DropDownItems
                If TypeOf (Item) Is ToolStripMenuItem Then
                    AddHandler Item.Click, AddressOf Menu_OnClick
                End If

            Next

    Next

De esta forma podes acceder a cada uno de los eventos en la siguiente forma

Private Sub Menu_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)

            Dim Frm As Form = GetFormByName(sender.name)
            If sender.Tag = "Modal" Then
                Frm.ShowDialog(Me)
            ElseIf sender.Tag = "Modeless" Then
                Frm.Show(Me)
            Else
                OpenForm(Frm, True)
            End If

    End Select