Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic Menu Clicking

Status
Not open for further replies.

markhkram

IS-IT--Management
Dec 30, 2008
32
US
Hi, My application has a Menu that has been dynamically created from files in a specific directory. I'm trying to edit the code so that if I click on one of those dynamically created Menu Items, I want it to MsgBox the item I clicked.

Here is what I have so far:
Code:
            For Each file In files
                If file <> "" Then
                    AddHandler LanguageToolStripMenuItem.DropDown.Click, AddressOf fileMenuItem_click
                End If
            Next

    Public Sub fileMenuItem_click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        MsgBox(LanguageToolStripMenuItem.DropDownItems.Item(1).Text)

    End Sub

The above code will msgbox the 2nd item of the dynamically created menu when I click on any item in the menu. Does anyone know how to make it msgbox the item clicked?

Thanks!
 
When you're looping through your files, you are setting the handler for the same exact object each time. You are not changing LanguageToolStripMenuItem at all.

Instead, assign the event handler as you are creating the new MenuItems. See the following example:

Code:
    'Add some menu items
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        For i As Integer = 0 To 9
            Dim tis As New ToolStripMenuItem("item " & i.ToString, Nothing, [COLOR=#ff0000][b]New EventHandler(AddressOf Me.MenuItem_Click)[/b][/color])  '= CType(Me.MenuStrip1.Items(0), ToolStripMenuItem)
            Dim parentmenu As ToolStripMenuItem = CType(Me.MenuStrip1.Items(0), ToolStripMenuItem)
            parentmenu.DropDownItems.Add(tis)
        Next
    End Sub

    'Display the text of the menu which was clicked
    Private Sub MenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim tis As ToolStripItem = CType(sender, ToolStripItem)
        MessageBox.Show(tis.Text)
    End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top