Adding Menus at runtime



In Visual Basic, adding menus at runtime is handled in the exact same way as adding any control at runtime. First you have to create a control array at design time, then at runtime you just load the new controls into the array. Here is the discussion to show you all the steps to handle this.
First, how to set up a menu control array at design time. Next, how to add more menus to your array at runtime. Finally,how to handle the click events of all the menus you add at runtime.

Open up a project in Visual Basic, and follow the steps.

Design Time

So, how do you create a menu control array at design time? Simple,
  • First right click any place on your form where there are no controls.
  • Then choose Menu Editor…
  • Now in the editor add a main menu,
  • Give it a caption such as Favorites and a name such as mnuFav.
  • Then click next,
  • Then the right arrow button so that the new menu will appear under it.
  • Now give this menu a fake caption for now like My Caption and give it a name such as mnuFavLinks.
  • Finally set its index property to 0. By setting its index property, you tell VB that you want this menu to be the first element in the control array.
That's all you have to do at design time.

Run Time

Now, at runtime to add a new menu to the menu control array you simply use the command: Load mnuFavsLinks(index) where index is the next number in the control array. For example you want three favorites under my Favorites menu.  You want them to show up as Favorite 1, Favorite 2, and Favorite 3.