2

I need to populate a context menu from a database at run time. I do not know the number of items that will be in the list, so I would like to handle the click event in a single place. How do I declare the handler so I can tell which menu item actually triggered the click.

Public Function GetBookmarkContextMenu(ByVal aBookmark As Bookmark) As System.Windows.Controls.ContextMenu

    Dim myContextMenu As New Controls.ContextMenu
    myContextMenu.Name = "BookmarkMenu" 

             For Each aMailingList As MasterService.FalconBookmarkMailingListType In GlobalUserSettings.MailingLists

                Dim mySubMenuItem As New Controls.MenuItem
                mySubMenuItem.Name = "MailingListName" & aMailingList.ID.ToString
                mySubMenuItem.Header = aMailingList.Title
                AddHandler (myMenuItem.Click), AddressOf ForwardToList_Click
                mySubMenuItem.IsEnabled = True
                myMenuItem.Items.Add(mySubMenuItem)
            Next
            myContextMenu.Items.Add(myMenuItem)

            return myContextMenu
End Function

Public Sub ForwardToList_Click()
    'How do I know which of the dynamically created items was clicked?
End Sub

3 Answers 3

3

Can't add a comment so I'll put it here. Excellent reply from AundyKarthick easily set out my result was this:

First create a contextmenustrip on the form in this case ContextMenuStrip1

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
  NamesTableAdapter.Fill(DataSet.Names)
  For Each element In DataSet.Names
     Dim mnuitem As New ToolStripMenuItem
     mnuitem.Name = element.Item(1)
     mnuitem.Text = element.Item(1)
     AddHandler (mnuitem.Click), AddressOf ToolMenuItem_Click
     ContextMenuStrip1.Items.Add(mnuitem)
  Next
End Sub

Private Sub ToolMenuItem_Click(sender As Object, ByVal e As EventArgs) 
    textbox1.Text = sender.name
End Sub
Sign up to request clarification or add additional context in comments.

Comments

2
Dim mnuitm As New ToolStripMenuItem
mnuitm.Name = name_cbk.Items(i)
mnuitm.Text = name_cbk.Items(i)
AddHandler (mnuitm.Click), AddressOf item_Click
menulist.Items.Add(mnuitm)

Comments

0

Your ForwardToList_Click() should include parameters for the sender and event args:

Public Sub ForwardToList_Click(sender As Object, e As EventArgs)
'...
End Sub

"sender" is the control that caused the event, which is what I believe you're looking for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.