ContextMenuStrip event handler at runtime
vb.net
Solution
Each menu item needs the handler.
Try it this way (updated with adding a shortcut key):
For count As Integer = 0 To strArr.Length - 1
If strArr(count).Length > 1 Then
Dim newMenu As New ToolStripMenuItem(strArr(count), _
Nothing, AddressOf cMenu_Click)
newMenu.ShortcutKeys = Keys.Control Or Keys.C
.Items.Add(newMenu)
End If
Next
Your click method should be changed to handle a `ToolStripMenuItem` instead:
Private Sub cMenu_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim mytext As String
mytext = DirectCast(sender, ToolStripMenuItem).Text
Debug.Print(mytext)
End Sub
Problem
I create Context menu at runtime depends of text in selected cell of datagridview. Like this: ``` With ContextMenuStrip1 .Items.Clear() Dim Str As String = DataGridView1.Item(1, DataGridView1.CurrentRow.Index).Value Dim strArr() As String = Str.Split(" ") For count As Integer = 0 To strArr.Length - 1 If strArr(count).Length > 1 Then .Items.Add(strArr(count)) End If Next .Items.Add("-") .Items.Add("Common operation ...") .Items.Add("Second common operation ...") AddHandler .Click, AddressOf cMenu_Click .Show(New Point(Cursor.Position.X, Cursor.Position.Y)) End With etc... ``` Then I add event handler like this: ``` Private Sub cMenu_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim mytext As String mytext = (CType(sender, ContextMenuStrip).Text) Debug.Print(mytext) 'after all... RemoveHandler ContextMenuStrip1.Click, AddressOf cMenu_Click End Sub ``` And as vbnet beginner with this code I can't get text of fired menu item in event handler. So please help to get it.