What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleMake an infinitely cascading series of menu items in Visual Basic .NET
DescriptionThis example shows how to make an infinitely cascading series of menu items in Visual Basic .NET.
Keywordsmenus, runtime menus, run time menus, create menus, create menus at runtime, create menus at run time, Visual Basic .NET, VB.NET
CategoriesControls, Puzzles and Games

The example Create menu items at run time with images, shortcut keys, and event handlers in Visual Basic .NET explains how to create menu items at run time. This example uses that technique to add new menu items to any expanding submenu. The results is a series of cascading menu items that grows as you drill deeper into it.

At design time, I gave the program a Tools main menu with a Tools menu item. Both of those menu items use the following DropDownOpening event handler to take action when they open.

' This menu item is opening.
' Add an item to this item's submenu.
Private Sub mnuTools_DropDownOpening(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles _
    mnuToolsSub1.DropDownOpening, mnuTools.DropDownOpening

    ' Remove this item's event handler.
    Dim menu As ToolStripMenuItem = DirectCast(sender, _
    RemoveHandler menu.DropDownOpening, AddressOf _

    ' Find the submenu.
    Dim submenu As ToolStripMenuItem = _
        DirectCast(menu.DropDownItems(0), ToolStripMenuItem)

    ' Add the sub-submenu item.
    Dim new_item As New ToolStripMenuItem("&Tools")
    AddHandler new_item.DropDownOpening, AddressOf _
End Sub
This event handler finds the menu item that is opening and removes its event handler so this code isn't executed again for that item.

It then finds the item's single sub-item. That item has not yet been opened and does not yet contain any sub-items so, if the code did nothing else, the sub-item would appear as a normal menu item not a cascading menu. To fix that, the code adds a new menu item to the sub-item. It sets the new item's DropDownOpening event handler to the same one used by the other menu items so it can continue the game when it is eventually opened.

(No this isn't a good feature to add to a real application. It's just an exercise in creating menus at run time. It's also kind of funny.)

Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.