将处理程序添加到动态创建的上下文菜单

时间:2008-11-17 20:14:30

标签: vb.net events contextmenu

我需要在运行时从数据库填充上下文菜单。我不知道列表中的项目数量,所以我想在一个地方处理点击事件。如何声明处理程序,以便告诉哪个菜单项实际触发了点击。

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 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:1)

无法添加评论,所以我会把它放在这里。来自AundyKarthick的优秀回复很容易出发 我的结果是:

首先在表单上创建一个contextmenustrip,在本例中为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

答案 2 :(得分:0)

您的ForwardToList_Click()应包含发件人和事件参数的参数:

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

“sender”是导致该事件的控件,我相信您正在寻找。