Menu Object in VB.net

adwaitjoshi

Active member
Joined
Dec 29, 2005
Messages
38
Programming Experience
1-3
Hi,
Is there a menu object in VB.net which I can loop through and decide which menu item is to be shown to the user (Depending on the access) on the main window?
Adwait
 
Moved. Please post in the most appropriate forum.

I assume that you are using the IDE. Have you looked in the Toolbox? The MainMenu (.NET 1.x) or MenuStrip (.NET 2.0) are right there. You can add items to them in the designer. If you want to manipulate their properties at run time then you can do so directly through the member variables created for them. Why do you need a loop?
 
I have a static menu constructed at design time. What I want to do is depending on if a user has access to a particular menu item or not, I want to hide that menu item. I have the menu name and access mapping in a database. So Basically I want to loop through each menu item, see if the user has access to it or not and then hide it.
 
this worked only with the main menu options
I have the following structure

File
File -> Open
File -> Save

View
View -> Print Layout
View -> Full Layout

the code never went to sub options open, save, print layout, full layout etc. What do I need to do with the code to get it into the sub items?
 
Just store your menuitems in an array of menuitem and loop through it. Just like this one. I think there would be better way than this but this what I have in my mind so far.
VB.NET:
dim m() as menuitem={me.menuItem1,me.menuItem2,me.menuItem3}
foreach mm as menuitem in m then
MessageBox.Show(mm.Text)
next
 
There is nothing wrong with using an array as suggested but your MenuItems form a tree structure so I think you should use recursion to traverse them just as you should with any tree structure.
VB.NET:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.SetMenuItemStates(Me.Menu.MenuItems)
    End Sub

    Private Sub SetMenuItemStates(ByVal items As MenuItem.MenuItemCollection)
        For Each item As MenuItem In items
            'Set the state of the current item.
            item.Enabled = True

            'Call the metho drecursively to set the state of the subitems.
            Me.SetMenuItemStates(item.MenuItems)
        Next item
    End Sub
This method just enables each item but you can obviously adjust the code to do what you want.
 
Having said all this, each MenuItem has a corresponding member variable so you don't really need to traverse the menu. Can't you just write explicit code in the Load event handler, something like this:
VB.NET:
Me.MenuItem1.Enabled = (currentUser.Access = Administrator)
where you get the access level from a database or whatever and write one line for each menu item that has variable access.
 
Back
Top