vb.netdynamictoolstripmenutoolstripitem

VB.NET Execute code on events for dynamically added ToolStripMenuItem


VB.NET
On the opening of a menu item (i.e. the top-level menu item), i have added ToolStripMenuItem (i.e. DropDownItem) to the menu item at runtime.

The ToolStripMenuItems added by me during runtime are the names of the forms active in the current project.

Whenever the ToolStripMenuItem with a particular form name is clicked, the form should be given focus.

How can i execute the desired code for the event of a dynamically added ToolStripMenuItem?

Private Sub WindowToolStripMenuItem_DropDownOpening(sender As Object, e As System.EventArgs) Handles WindowToolStripMenuItem.DropDownOpening
        WindowToolStripMenuItem.DropDown.Items.Clear()

        For Each Form In My.Application.OpenForms
            If Not Form.name = frmLogin.Name And Not Form.name = Me.Name Then
                Dim tmiForm = New ToolStripMenuItem()
                tmiForm.Name = Form.name
                tmiForm.Text = Form.text
                WindowToolStripMenuItem.DropDownItems.Add(tmiForm)
            End If
        Next

    End Sub


i want to give focus to a form based on the tmiForm's click event...
i tried searching on the web i only got results for C#


Solution

  • try this-

    Private Sub clickeventhandler(sender As Object, e As EventArgs)
        For Each Form In My.Application.OpenForms
            If CType(sender, ToolStripMenuItem).Name = Form.Name Then
                Form.Focus()
                Exit Sub
            End If
        Next
    End Sub
    

    your previous code seems fine just add a single line.
    After

    WindowToolStripMenuItem.DropDownItems.Add(tmiForm)
    

    write this-

    AddHandler tmiForm.Click, AddressOf clickeventhandler