VB.NET Execute code on events for dynamically added ToolStripMenuItem

Shraavan Acharya picture Shraavan Acharya · Mar 19, 2013 · Viewed 7.2k times · Source

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#

Answer

Neolisk picture Neolisk · Mar 19, 2013

Use AddHandler:

AddHandler tmiForm.Click, AddressOf ClickHandler

Here is how you can write your ClickHandler:

Public Sub ClickHandler(ByVal sender As Object, ByVal e As EventArgs)
  'for a condition based on a ToolStripMenuItem that fired it
  'If CType(sender, ToolStripMenuItem).Name ...
End Sub