VB.Net Menuitem added dynamically not firing click event

654 Views Asked by At

I am completely lost here. I have dynamically created a menuitem. I've added an onclick-event handler, but this code never seems to fire. I remember it working a few months back and don't recall making any changes to it, but it's possibly something stupid that I've done.

Please see my code below:

frmMain._mnuSep1_0.Visible = True
Dim tlRecentApp As New ToolStripMenuItem(strMenuCaption)
tlRecentApp.Text = "Test"
tlRecentApp.Name = "AddApp"
tlRecentApp.Tag = strMenuID
RecentAppID = strMenuID
AddHandler tlRecentApp.Click, AddressOf Test
frmMain.mnuApplicantS.DropDownItems.Add(tlRecentApp.ToString)

The code for the Event:

Public Sub MnuRecentApp(ByVal sender As Object, ByVal e As EventArgs)
   ' MsgBox(sender.tag.ToString)
    ApplicantID = sender.tag.ToString
    frmApplicantEdit.Show()
End Sub

It gets created but when I click on it nothing happens:

4

There are 4 best solutions below

0
On

I found the problem. This line:

frmMain.mnuApplicantS.DropDownItems.Add(tlRecentApp.ToString)

Should read:

frmMain.mnuApplicantS.DropDownItems.Add(tlRecentApp)
1
On

If the code for the event handler is

Public Sub MnuRecentApp(ByVal sender As Object, ByVal e As EventArgs)
   ' MsgBox(sender.tag.ToString)
    ApplicantID = sender.tag.ToString
    frmApplicantEdit.Show()
End Sub

then this line

AddHandler tlRecentApp.Click, AddressOf Test

should be

AddHandler tlRecentApp.Click, AddressOf MnuRecentApp
0
On

Just In case anyone else has this problem. I had an instance where it seemed my item click event was not firing. It turned out I had removed the handler too early (it was dynamic menu). I had removed the handler in the closed event of the Parent Menu (not kept open). It seems that parent close event is fired before the click event of the item is considered.

3
On

Without trying to change too much of your code I've tested the following successfully:

Control:

Dim tlRecentApp As New ToolStripMenuItem(strMenuCaption)
'tlRecentApp.Text = "Test"  This isn't needed as it's done on the above line when declared
tlRecentApp.Name = "AddApp"
tlRecentApp.Tag = strMenuID
RecentAppID = strMenuID
AddHandler tlRecentApp.Click, AddressOf MnuRecentApp
frmMain.mnuApplicantS.Items.Add(tlRecentApp)

Method:

Public Sub MnuRecentApp(ByVal sender As Object, ByVal e As EventArgs)
    ApplicantID = CType(sender, ToolStripMenuItem).Tag.ToString
    frmApplicantEdit.Show()
End Sub

mnuApplicantS is a ToolStrip control in my example. If you could clarify what mnuApplicatS is in your application I might be able to provide a better solution.