5

I can perform the submenu list down using the codes below:

Dim cm As GoContextMenu = New GoContextMenu(view) 'GoContextMenu  Inherits System.Windows.Forms.ContextMenu 

Dim subTop(1) As MenuItem      ' if you have 2 submenu, then the array count is 2-1 = 1; subm(1)          
Dim orMenu As New MenuItem("OR", New EventHandler(AddressOf Me.OrTopGateItem_Click))
Dim andMenu As New MenuItem("AND", New EventHandler(AddressOf Me.AndTopGateItem_Click))

cm.MenuItems.Add(New MenuItem("Type", subTop))

From the case above, I manage to create a submenu which is shown in the image below: screen shot of my submenu outcome

How can I dynamically add more submenu during run time?

Thank you.

Saro Taşciyan
  • 5,210
  • 5
  • 31
  • 50
user2150279
  • 445
  • 2
  • 8
  • 17
  • What exactly do you want to add? You cannot add just *anything*, because for those you won't have a handler declared. Please provide more details. – Victor Zakharov Apr 17 '14 at 16:54
  • @Neolisk, in the sample code above, I need to manually create an array and define the size before I execute the program as I know the number of items in the menu. Now the number of item is unknown until during run time, how do I dynamically add those items to the sub menu? – user2150279 Apr 17 '14 at 16:55
  • I am still having trouble understanding your requirement. What do you expect to get in the end? How would you populate those dynamic items, assuming a number of them is known at compile time (=they are static). Please show relevant code. – Victor Zakharov Apr 17 '14 at 18:08
  • You do it the same way you did during design time. See the code below from MSDN. – John Apr 17 '14 at 20:34

1 Answers1

13
Public Class Form1


    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        Me.ContextMenuStrip = ContextMenuStrip1

        Dim menu1 As New ToolStripMenuItem() With {.Text = "Menu Item 1", .Name = "mnuItem1"}
        AddHandler menu1.Click, AddressOf mnuItem_Clicked
        ContextMenuStrip1.Items.Add(menu1)

        'Add a submenu to Menu 1
        Dim menu2 As New ToolStripMenuItem() With {.Text = "Menu Item 2", .Name = "mnuItem2"}
        'We have a reference to menu1 already, but here's how you can find the menu item by name...
        For Each item As ToolStripMenuItem In ContextMenuStrip1.Items
            If item.Name = "mnuItem1" Then
                item.DropDownItems.Add(menu2)
                AddHandler menu2.Click, AddressOf mnuItem_Clicked
            End If
        Next


    End Sub

    Private Sub mnuItem_Clicked(sender As Object, e As EventArgs)
        ContextMenuStrip1.Hide() 'Sometimes the menu items can remain open.  May not be necessary for you.
        Dim item As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)
        If item IsNot Nothing Then
            MsgBox("You've clicked " & item.Name)
        End If
    End Sub

End Class
John
  • 1,310
  • 3
  • 32
  • 58