Click here to Skip to main content
15,888,816 members
Articles / Programming Languages / Visual Basic
Article

Dynamic Creation Of MenuStrip - VB.NET

Rate me:
Please Sign up or sign in to vote.
3.96/5 (15 votes)
23 Aug 2008CPOL1 min read 233.3K   9.7K   64   50
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

Image 1

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.

VB.NET
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.

VB.NET
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".

VB.NET
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:

VB.NET
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)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHacking Access database Pin
Gyanendra kumar thakur29-Jun-07 19:07
Gyanendra kumar thakur29-Jun-07 19:07 
AnswerRe: Hacking Access database Pin
Bad Programmer30-Jun-07 9:43
Bad Programmer30-Jun-07 9:43 
QuestionUse the 'new' keyword to create an object instance. Pin
keonj26-Jun-07 12:00
keonj26-Jun-07 12:00 
AnswerRe: Use the 'new' keyword to create an object instance. Pin
Bad Programmer30-Jun-07 11:17
Bad Programmer30-Jun-07 11:17 
GeneralRe: Use the 'new' keyword to create an object instance. Pin
Dustin Klinkenberg20-Aug-08 7:53
Dustin Klinkenberg20-Aug-08 7:53 
GeneralRe: Use the 'new' keyword to create an object instance. Pin
Alicealiciasawarak28-Mar-11 19:00
Alicealiciasawarak28-Mar-11 19:00 
GeneralCreate a Connection class Pin
GeertD19-Jun-07 0:52
GeertD19-Jun-07 0:52 
GeneralRe: Create a Connection class Pin
Bad Programmer5-Nov-08 1:22
Bad Programmer5-Nov-08 1:22 
apologize for long delay.

please dont use the below class, i created this at the start of my carrer and it has lot of issues.

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.SqlClient
Public Class Conn1
Private oConn As SqlConnection
Private oCommand As New SqlCommand
Private oReader As SqlDataReader
Private oDataAdapder As New SqlDataAdapter
Private inCommand As New SqlCommand
Private connstring As String = Nothing
'openconnection
Public Sub openconnection()
Try
If connstring Is Nothing Then
connstring = ReadConnectionString()
End If
oConn = New SqlConnection(connstring)
If oConn.State = ConnectionState.Open Then
oConn.Close()
End If
oConn.Open()
Catch Ex As Exception
Dim uObj As New BasicFunctions
uObj.logoutAgent()
'Throw New System.Exception("Error Source: Connection " + Ex.Message)
End Try
End Sub 'openconnection
' Close Connection
Private Sub closeconnection()
Try
If oConn.State = ConnectionState.Open Then
oConn.Close()
oConn = Nothing
End If
Catch Ex As Exception
'Throw New System.Exception("Error Source: Connection " + Ex.Message)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
End Try
End Sub 'closeconnection
'Read Connection String
Private Function ReadConnectionString() As String
connstring = "Data Source=;Initial Catalog=;User Id=;Password=;"
Return connstring
End Function
'DataReader with a select statement3
Public Function ReaderData(ByVal mySelectQuery As String) As SqlDataReader
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(mySelectQuery, oConn)
oCommand.CommandTimeout = 90
'oReader = oCommand.ExecuteReader(CommandBehavior.CloseConnection)
oReader = oCommand.ExecuteReader
Return oReader
Catch ex As Exception
'Throw New System.Exception("Error Source: Connection " + ex.Message + mySelectQuery)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
End Try 'myReader = null;
End Function 'ReaderData
'Insert routine
Public Function Insert(ByVal myInsertQuery As String) As Object
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(myInsertQuery, oConn)
oCommand.CommandTimeout = 90
oCommand.ExecuteNonQuery()
'oReader = oCommand.ExecuteReader(CommandBehavior.CloseConnection)
Return "0"
Catch ex As Exception
'Throw New System.Exception("Error Source: Connection " + ex.Message + myInsertQuery)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
'oCommand = Nothing
'oConn = Nothing
End Try 'myReader = null;
End Function
'Insert routine With Identity fetching
Public Function Insert(ByVal myInsertQuery As String, ByVal strPar As String) As Integer
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(myInsertQuery, oConn)
oCommand.Parameters.Add(New SqlParameter("@SrID", SqlDbType.Int))
oCommand.Parameters("@SrID").Direction = ParameterDirection.Output
oCommand.Parameters("@SrID").SourceColumn = strPar
oCommand.CommandTimeout = 90
Return Convert.ToInt16(oCommand.ExecuteScalar)
Catch ex As Exception
'Throw New System.Exception("Error Source: Connection " + ex.Message + myInsertQuery)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
oConn = Nothing
End Try 'myReader = null;
End Function
'Execute routine
Public Function ExScalar(ByVal myInsertQuery As String) As String
Try
Dim objcon As Object = oConn
Dim strResult As String
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(myInsertQuery, oConn)
oCommand.CommandTimeout = 90
strResult = oCommand.ExecuteScalar().ToString
Return strResult
Catch ex As Exception
'Throw New System.Exception("Error Source: Connection " + ex.Message + myInsertQuery)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
oConn = Nothing
End Try 'myReader = null;
End Function
'Fill DataTable
Public Function FillSPDataTable(ByVal MySelectQuery As String) As DataTable
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(MySelectQuery, oConn)
Dim MyDataTable As New DataTable
oDataAdapder = New SqlDataAdapter(oCommand)
oCommand.CommandTimeout = 300
oCommand.CommandType = CommandType.StoredProcedure
oDataAdapder.Fill(MyDataTable)
Return MyDataTable
Catch ex As Exception
'Throw New System.Exception(ex.Message)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
closeconnection()
End Try
End Function
'Fill DataTable
Public Function FillDataTable(ByVal MySelectQuery As String) As DataTable
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(MySelectQuery, oConn)
Dim MyDataTable As New DataTable
oDataAdapder = New SqlDataAdapter(oCommand)
oCommand.CommandTimeout = 300
oCommand.CommandType = CommandType.Text
oDataAdapder.Fill(MyDataTable)
Return MyDataTable
Catch ex As Exception
'Throw New System.Exception(ex.Message)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
closeconnection()
End Try
End Function
'Fill Dataset
Public Function FillDataSet(ByVal MySelectQuery As String) As DataSet
Try
Dim objcon As Object = oConn
If objcon Is Nothing Then
openconnection()
End If
oCommand = New SqlCommand(MySelectQuery, oConn)
Dim MyDataSet As New DataSet
oDataAdapder = New SqlDataAdapter(oCommand)
oCommand.CommandTimeout = 300
oCommand.CommandType = CommandType.Text
oDataAdapder.Fill(MyDataSet, "myTable")
Return MyDataSet
Catch ex As Exception
'Throw New System.Exception(ex.Message)
Dim uObj As New BasicFunctions
uObj.logoutAgent()
Return Nothing
Finally
oCommand = Nothing
closeconnection()
End Try
End Function
End Class

Bad Programmer

QuestionRe: Create a Connection class Pin
GeertD5-Nov-08 1:49
GeertD5-Nov-08 1:49 
AnswerRe: Create a Connection class Pin
Bad Programmer5-Nov-08 19:47
Bad Programmer5-Nov-08 19:47 
GeneralArticle missing pic Pin
J Sullivan17-Jun-07 16:29
J Sullivan17-Jun-07 16:29 
GeneralRe: Article missing pic Pin
Bad Programmer18-Jun-07 10:20
Bad Programmer18-Jun-07 10:20 

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

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