Previous | Index | Next 

[PRB] Arrays of menu items can throw an exception if items are destroyed too early

VB6 and VB.NET deal with menu items in different ways. More specifically, VB6 allows you to dynamically create a submenu or a context menu immediately before displaying it, and to destroy it immediately afterwards. This feature allows VB6 developers to create dynamic menus based on control arrays, using the following sequence of actions:

  1. add elements to the menu control array by means of the array’s Load method
  2. display a context menu using the PopupMenu method
  3. destroy elements that were added in point 1, by means of the Unload method

This sequence works correctly because VB6 is able to process the Click event from an element of the menu array even if the element has been unloaded in the meantime.

Conversely, VB.NET requires that the menu elements exist at the instant when the Click event is processed. For this reason the above sequence of actions throws an exception after being migrated to VB.NET. You have to manually edit the code to abide to the following sequence:

  1. destroy any element that was added during a previous iteration, by means of the Unload method
  2. add elements to the menu control array, by means of the Load method
  3. display a context menu using the PopupMenu method

In other words, instead of destroying all menu items immediately after displaying the menu, you should add programming logic that destroy any old element and then rebuilds the menu immediately before displaying the popup menu.

 

Previous | Index | Next