Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 747
  • Last Modified:

handling events for context menu items

I add menu items to my context menu strip, and then add a hanler for the click event.  In the subroutine, how can I tell which menu item was clicked?

I'm familiar with the static context menu strip where I can use "sender.tostring", but I don't think that will work for my runtime context menu strip.

In the form_load subroutine:

For each cgems in listArray
  Dim Y As New ToolStripMenuItem
  Y.Text = cgems
  Y.CheckOnClick = True
  Y.DisplayStyle = ToolStripItemDisplayStyle.Text
  AddHandler Y.Click, AddressOf Me.clickCGEMS
  cmsCgems.Items.Add(Y)
Next

0
motokent
Asked:
motokent
1 Solution
 
AngryBinaryCommented:
You can still use the "sender" property to determine which menu item was clicked on. You can use the "Text" property to differentiate menu items assuming they all have different "Text" values, though you may want to look into the "ToolStripMenuItem.Tag" property:

Protected Sub clickCGEMS (sender as Object, e as EventArgs)
    Dim item as ToolStripMenuItem = CType(sender, ToolStripMenuItem)
    If item.Text = "Menu option 1" Then
         'Do some stuff...
    Else If item.Text = "Menu option 2" Then
         'Do some other stuff...
    End If
End Sub

If you are binding that click handler to objects other than menu items, you will want to check their type before doing the CType cast:

Protected Sub clickCGEMS (sender as Object, e as EventArgs)
    If TypeOf(sender) is ToolStripMenuItem Then
        Dim item as ToolStripMenuItem = CType(sender, ToolStripMenuItem)
        'Do some stuff...
    Else If TypeOf(sender) is Button Then
        Dim button as Button = CType(sender, Button)
        'Do some other stuff
    End If
End Sub




0
 
motokentAuthor Commented:
Thanks!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now