Click here to Skip to main content
6,595,854 members and growing! (17,472 online)
Email Password   helpLost your password?
Languages » VB.NET » General     Intermediate License: The Code Project Open License (CPOL)

Dynamic Creation Of MenuStrip - VB.NET

By Bad Programmer

Implementing Menustrip dynamically from database, the menu names and order will be through backend.
VB 8.0, Windows, .NET CF, .NET 2.0VS2005, Dev
Posted:17 Jun 2007
Updated:24 Aug 2008
Views:45,405
Bookmarked:43 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
9 votes for this article.
Popularity: 3.27 Rating: 3.43 out of 5

1
2 votes, 22.2%
2
2 votes, 22.2%
3

4
5 votes, 55.6%
5

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)

About the Author

Bad Programmer


Member

Location: United States United States

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 29 (Total in Forum: 29) (Refresh)FirstPrevNext
GeneralMainMenu twice click from first form load PinmemberMember 27286832:28 24 Jul '09  
QuestionRe: MainMenu twice click from first form load PinmemberJuan Camilo Arboleda17:10 1 Aug '09  
GeneralDynamic Creation Of MenuStrip - C#.NET PinmemberSameeraMadhawa23:34 23 Jul '09  
GeneralRe: Dynamic Creation Of MenuStrip - C#.NET PinmemberMoises Torres11:44 10 Sep '09  
GeneralProblem in DynamicallyLoadedObject() PinmemberArul Soosai22:07 12 Apr '09  
GeneralRe: Problem in DynamicallyLoadedObject() PinmemberArul Soosai22:32 12 Apr '09  
GeneralRe: Problem in DynamicallyLoadedObject() PinmemberBad Programmer2:03 13 Apr '09  
GeneralRe: Problem in SelectedchildMenu_OnClick event PinmemberArul Soosai23:00 14 Apr '09  
GeneralRe: Problem in SelectedchildMenu_OnClick event PinmemberBad Programmer19:27 18 Apr '09  
QuestionDynamic Creation of MenuStrip- C#.net [modified] PinmemberShahid K2:24 5 Mar '09  
GeneralResult listed by vertical, not horizontal PinmemberHendra Prasetyo17:59 15 Jan '09  
AnswerRe: Result listed by vertical, not horizontal PinmemberBad Programmer21:51 15 Jan '09  
Generalopen dynamic form in MDI window PinmemberMithuya9:05 4 Nov '08  
GeneralRe: open dynamic form in MDI window PinmemberBad Programmer2:13 5 Nov '08  
GeneralExcelent Pinmemberlefaconi6:06 25 Oct '08  
GeneralRe: Excelent PinmemberMithuya9:04 4 Nov '08  
GeneralSimple superb Pinmemberashu fouzdar21:43 26 Aug '08  
GeneralDownload code Pinmemberbkresimir20:30 25 Feb '08  
QuestionHacking Access database PinmemberGyanendra kumar thakur20:07 29 Jun '07  
AnswerRe: Hacking Access database PinmemberBala J10:43 30 Jun '07  
QuestionUse the 'new' keyword to create an object instance. Pinmemberkeonj13:00 26 Jun '07  
AnswerRe: Use the 'new' keyword to create an object instance. PinmemberBala J12:17 30 Jun '07  
GeneralRe: Use the 'new' keyword to create an object instance. PinmemberDustin Klinkenberg8:53 20 Aug '08  
GeneralCreate a Connection class PinmemberGeertD1:52 19 Jun '07  
GeneralRe: Create a Connection class PinmemberBad Programmer2:22 5 Nov '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Aug 2008
Editor: Deeksha Shenoy
Copyright 2007 by Bad Programmer
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project