Shai
Shai

Reputation: 569

Handling onclick event of Contextmenu Menu Item on windows form

I have Windows Form App. I have added Context Menu that appear when you right mouse click over the listbox. But some reason I could not figure out how to catch onClick event for ContextMenu- Menu-Item. In also need to grab item index from the listbox while user click on menu-item. If I am clicking the left mouse button i would use lstCustomer.SelectedItems(0).SubItems(2).Text, but I am not sure would it be the same case or not when user right clicks over the item and pick menu-item from Context Menu.

Dashboard.vb

Public Class Dashboard
  Private Sub Dashboard_Load(ByVal sender As System.Object, ByVal e As 
  System.EventArgs) Handles MyBase.Load
    LoadContextMenu()
End Sub


Private Sub LoadContextMenu()
    Dim contxMnu As New ContextMenu()
    Dim menuItem1 As New MenuItem()
    Dim menuItem2 As New MenuItem()

      contxMnu.MenuItems.AddRange(New MenuItem() {menuItem1, menuItem2})

      menuItem1.Index = 0
      menuItem1.Text = "Do Something 1"

      menuItem2.Index = 1
      menuItem2.Text = "Do Something 2"

      Me.ContextMenu = contxMnu
    End Sub

End Class

Upvotes: 1

Views: 2895

Answers (1)

Michał Powaga
Michał Powaga

Reputation: 23183

I'm not sure whether I understand exactly what you want to get. If it's all about action that handles the Click event you can do something like this:

Private Sub LoadContextMenu()
    Dim contxMnu As New ContextMenu()
    Dim menuItem1 As New MenuItem("Do Something 1", New EventHandler(AddressOf DoSomething1))
    Dim menuItem2 As New MenuItem("Do Something 2", New EventHandler(AddressOf DoSomething2))

    contxMnu.MenuItems.AddRange(New MenuItem() {menuItem1, menuItem2})

    Me.ContextMenu = contxMnu
End Sub

...and events are:

Private Sub DoSomething1(sender As Object, e As EventArgs)
    ' do something 1 
End Sub


Private Sub DoSomething2(sender As Object, e As EventArgs)
    ' do something 2 
End Sub

Upvotes: 3

Related Questions