Click here to Skip to main content
11,633,425 members (79,546 online)
Click here to Skip to main content

Dynamic Creation Of MenuStrip - VB.NET

, 23 Aug 2008 CPOL 144.9K 6.6K 60
Rate this:
Please Sign up or sign in to vote.
Implementing Menustrip dynamically from database, the menu names and order will be through backend.

Introduction

I came up with the problem of creating an application that was driven according to user rights. I thought of implementing the menus to be driven through BackEnd. All the menu names and the form (formname) to open when the child menu was clicked, come from the table. To implement menus, I used MenuStrip from VB.NET.

Sample Code

Using the Code

It executes during the Form Load and populates all the menu headers. All data comes from the backend and there is nothing to hardcode. I have attached the structure of two tables MENUMASTER and ACCESS below.

The code below will have a variable like iUserAccessMode, which in turn tells us about the user access level (Look into the Excel sheet which has been attached and look into the Access Tab in the Excel sheet). The Menus will be loaded according to User Access Level.

 Private Sub MDIParent1_Load(ByVal sender As Object,
        ByVal e As System.EventArgs) Handles Me.Load
        'On Error GoTo ErrHandler
 'Create a Connection class, that has the full features of working with Backend.
 'See article for Connection class :  Connection_Class.asp
 
        Dim Conn As New Conn1
        Dim mnRd As SqlClient.SqlDataReader
 'It helps in populating the MENUs according to user rights. From the Table "Access"
        iUserAccessMode = GlobalValues.lblUsrAccess.Text
        sQry = ""
        sQry = "Select MenuText from MenuMaster Where MainMenuID = 0" & _
               " And MenuID in (Select MenuID from Access Where AccessId =
                " & CInt(iUserAccessMode) & ")" & _
                " And isActive = 1"
        mnRd = Conn.ReaderData(sQry)
        
 If mnRd.HasRows Then
            mnMenu = New MenuStrip
            While mnRd.Read
                mnMenu.Items.Add(mnRd(0).ToString, Nothing, New System.EventHandler(
                    AddressOf MainMenu_OnClick))
                Me.Controls.Add(mnMenu)
            End While
        End If
        
 mnRd.Close()
    End Sub

This function creates child menus when the parent menu is created.

Private Sub MainMenu_OnClick(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim cms As New ContextMenuStrip()
        Dim sMenu() As String
        Dim Conn As New Conn1
        Dim sMenuRD As SqlClient.SqlDataReader
        sQry = ""
        sQry = "Select MenuID from MenuMaster Where MenuText = '" & sender.ToString & "'"
        sMenuRD = Conn.ReaderData(sQry)
        Dim parentMenuID As Integer
        If sMenuRD.HasRows Then
            sMenuRD.Read()
            parentMenuID = sMenuRD("MenuID")
        End If
        sMenuRD.Close()
        sQry = ""
        sQry = "Select MenuText from MenuMaster Where MainMenuID =
               '" & parentMenuID & "'" & _
               " And isActive = 1" & _
               " And MenuID in (
                   Select MenuID from Access Where AccessId =
                   " & CInt(iUserAccessMode) & ")" & _
               " Order BY MenuOrder"
        sMenuRD = Conn.ReaderData(sQry)
        ReDim Preserve sMenu(0)
        Dim i As Integer
        If sMenuRD.HasRows Then
            ReDim Preserve sMenu(0)
            i = 0
            While sMenuRD.Read()
                ReDim Preserve sMenu(i)
                sMenu(i) = sMenuRD("MenuText")
                i = i + 1
            End While
        End If
        sMenuRD.Close()
        For Each sMn As String In sMenu
            cms.Items.Add(sMn, Nothing,
                New System.EventHandler(AddressOf SelectedChildMenu_OnClick))
        Next
        Dim tsi As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
        tsi.DropDown = cms
    End Sub

This function is executed at the click event of each menu item, the form to open(FormName) on the execution of the event also comes from the backend table "MENUMASTER".

    Private Sub SelectedChildMenu_OnClick(ByVal sender As Object,
        ByVal e As System.EventArgs)
        Dim Conn As New Conn1
        Dim sMenuRD As SqlClient.SqlDataReader
        Dim frmName As String = ""
        Dim frm As New Form
        sQry = ""
        sQry = "Select FormName from MenuMaster Where MenuText = '" &
            sender.ToString & "'"
        sMenuRD = Conn.ReaderData(sQry)
        If sMenuRD.HasRows Then
            sMenuRD.Read()
            frmName = sMenuRD(0).ToString
            DynamicallyLoadedObject(frmName).Show(Me)
        Else
            MsgBox("Under Construction", MsgBoxStyle.Exclamation, "Technical Error")
        End If
        sMenuRD.Close()
    End Sub

Points of Interest

I came up with the problem of converting the formname which I get from SQL as string to FORM object. This function helps in converting the string object formName, which is returned from SQL into object of type Form:

    Private Function DynamicallyLoadedObject(ByVal objectName As String,
        Optional ByVal args() As Object = Nothing) As Form
        Dim returnObj As Object = Nothing
        Dim Type As Type = Assembly.GetExecutingAssembly().GetType(
            "[YOUR PROJECT NAME]." & objectName)
        If Type IsNot Nothing Then
            returnObj = Activator.CreateInstance(Type, args)
        End If
        Return returnObj
    End Function

History

  • 17th June, 2007: Initial post

License

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

Share

About the Author

Bad Programmer
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

 
Questionsample solution Pin
Member 105035684-Jan-14 10:50
memberMember 105035684-Jan-14 10:50 
QuestionObject reference not set to an instance of an object Pin
ajay170615-Dec-12 21:50
memberajay170615-Dec-12 21:50 
QuestionPlease help... Pin
shahidzahoor22-Aug-12 20:32
membershahidzahoor22-Aug-12 20:32 
QuestionProbleme sur menu dynamique Pin
abraoui20-Jul-12 2:42
memberabraoui20-Jul-12 2:42 
QuestioniUserAccessMode ? Pin
shahidzahoor18-Jul-12 9:30
membershahidzahoor18-Jul-12 9:30 
Questionhow to add icon to the menustrip item Pin
siva778418-Aug-11 0:39
membersiva778418-Aug-11 0:39 
how to add icon to the menustrip item
GeneralObject reference not set to an instance of an object. Pin
Alicealiciasawarak28-Mar-11 15:23
memberAlicealiciasawarak28-Mar-11 15:23 
GeneralRe: Object reference not set to an instance of an object. Pin
TheXeon198112-Nov-11 5:26
memberTheXeon198112-Nov-11 5:26 
GeneralName 'Assembly' is not declared Pin
Alicealiciasawarak28-Mar-11 2:12
memberAlicealiciasawarak28-Mar-11 2:12 
GeneralRe: Name 'Assembly' is not declared Pin
Bad Programmer31-Mar-11 12:03
memberBad Programmer31-Mar-11 12:03 
Questionhow to show the 3 level menu Pin
y2yawar12-Jan-10 19:10
membery2yawar12-Jan-10 19:10 
GeneralMainMenu twice click from first form load Pin
Member 272868324-Jul-09 1:28
memberMember 272868324-Jul-09 1:28 
QuestionRe: MainMenu twice click from first form load Pin
Juan Camilo Arboleda1-Aug-09 16:10
memberJuan Camilo Arboleda1-Aug-09 16:10 
AnswerRe: MainMenu twice click from first form load Pin
Mark Denson16-Nov-09 6:58
memberMark Denson16-Nov-09 6:58 
GeneralRe: MainMenu twice click from first form load Pin
wallaces52816-Nov-09 16:52
memberwallaces52816-Nov-09 16:52 
GeneralDynamic Creation Of MenuStrip - C#.NET Pin
SameeraMadhawa23-Jul-09 22:34
memberSameeraMadhawa23-Jul-09 22:34 
GeneralRe: Dynamic Creation Of MenuStrip - C#.NET Pin
Moises Torres10-Sep-09 10:44
memberMoises Torres10-Sep-09 10:44 
GeneralProblem in DynamicallyLoadedObject() Pin
Arul Soosai12-Apr-09 21:07
memberArul Soosai12-Apr-09 21:07 
GeneralRe: Problem in DynamicallyLoadedObject() Pin
Arul Soosai12-Apr-09 21:32
memberArul Soosai12-Apr-09 21:32 
GeneralRe: Problem in DynamicallyLoadedObject() Pin
Bad Programmer13-Apr-09 1:03
memberBad Programmer13-Apr-09 1:03 
GeneralRe: Problem in SelectedchildMenu_OnClick event Pin
Arul Soosai14-Apr-09 22:00
memberArul Soosai14-Apr-09 22:00 
GeneralRe: Problem in SelectedchildMenu_OnClick event Pin
Bad Programmer18-Apr-09 18:27
memberBad Programmer18-Apr-09 18:27 
GeneralRe: Problem in DynamicallyLoadedObject() Pin
Alicealiciasawarak28-Mar-11 18:38
memberAlicealiciasawarak28-Mar-11 18:38 
GeneralRe: Problem in DynamicallyLoadedObject() Pin
Alicealiciasawarak30-Mar-11 20:55
memberAlicealiciasawarak30-Mar-11 20:55 
QuestionDynamic Creation of MenuStrip- C#.net [modified] Pin
Shahid K5-Mar-09 1:24
memberShahid K5-Mar-09 1:24 
GeneralResult listed by vertical, not horizontal Pin
Hendra Prasetyo15-Jan-09 16:59
memberHendra Prasetyo15-Jan-09 16:59 
AnswerRe: Result listed by vertical, not horizontal Pin
Bad Programmer15-Jan-09 20:51
memberBad Programmer15-Jan-09 20:51 
Generalopen dynamic form in MDI window Pin
Mithuya4-Nov-08 8:05
memberMithuya4-Nov-08 8:05 
GeneralRe: open dynamic form in MDI window Pin
Bad Programmer5-Nov-08 1:13
memberBad Programmer5-Nov-08 1:13 
GeneralRe: open dynamic form in MDI window Pin
Mark Denson16-Nov-09 7:01
memberMark Denson16-Nov-09 7:01 
GeneralRe: open dynamic form in MDI window Pin
Finder11511-Jun-11 21:10
memberFinder11511-Jun-11 21:10 
GeneralRe: open dynamic form in MDI window Pin
Finder11511-Jun-11 20:51
memberFinder11511-Jun-11 20:51 
GeneralExcelent Pin
lefaconi25-Oct-08 5:06
memberlefaconi25-Oct-08 5:06 
GeneralRe: Excelent Pin
Mithuya4-Nov-08 8:04
memberMithuya4-Nov-08 8:04 
GeneralSimple superb Pin
ashu fouzdar26-Aug-08 20:43
memberashu fouzdar26-Aug-08 20:43 
GeneralDownload code Pin
bkresimir25-Feb-08 19:30
memberbkresimir25-Feb-08 19:30 
QuestionHacking Access database Pin
Gyanendra kumar thakur29-Jun-07 19:07
memberGyanendra kumar thakur29-Jun-07 19:07 
AnswerRe: Hacking Access database Pin
Bala J30-Jun-07 9:43
memberBala J30-Jun-07 9:43 
QuestionUse the 'new' keyword to create an object instance. Pin
keonj26-Jun-07 12:00
memberkeonj26-Jun-07 12:00 
AnswerRe: Use the 'new' keyword to create an object instance. Pin
Bala J30-Jun-07 11:17
memberBala J30-Jun-07 11:17 
GeneralRe: Use the 'new' keyword to create an object instance. Pin
Dustin Klinkenberg20-Aug-08 7:53
memberDustin Klinkenberg20-Aug-08 7:53 
GeneralRe: Use the 'new' keyword to create an object instance. Pin
Alicealiciasawarak28-Mar-11 19:00
memberAlicealiciasawarak28-Mar-11 19:00 
GeneralCreate a Connection class Pin
GeertD19-Jun-07 0:52
memberGeertD19-Jun-07 0:52 
GeneralRe: Create a Connection class Pin
Bad Programmer5-Nov-08 1:22
memberBad Programmer5-Nov-08 1:22 
QuestionRe: Create a Connection class Pin
GeertD5-Nov-08 1:49
memberGeertD5-Nov-08 1:49 
AnswerRe: Create a Connection class Pin
Bad Programmer5-Nov-08 19:47
memberBad Programmer5-Nov-08 19:47 
GeneralArticle missing pic Pin
Jared James Sullivan17-Jun-07 16:29
memberJared James Sullivan17-Jun-07 16:29 
GeneralRe: Article missing pic Pin
Bala_se18-Jun-07 10:20
memberBala_se18-Jun-07 10:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150728.1 | Last Updated 24 Aug 2008
Article Copyright 2007 by Bad Programmer
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid