Events on dynamic menu items???

charbaugh77

New member
Joined
Mar 20, 2011
Messages
3
Programming Experience
Beginner
I have a context menu control that loads items when right clicked. I want this menu to be defined by the user using an xml file. This part works. The next step I need help with. When the user clicks on a menu item loaded from the xml file I need it to raise the click event. I'm not sure...kinda new to creating events like this. I've seen it done in similar manner on other apps, but don't remember how. Thanks for your help!
 
You need to write the method that will handle the event beforehand of course. When you create the menu item, you specify what method will handle the Click event then, e.g.
VB.NET:
Dim menuItem As New TooStripMenuItem(menuText, menuIcon, AddressOf MenuClickEventHandler)
 
Thanks for the reply, but i do not follow.

I have a function that is called when the menu loads, to load the xml menu items. It works good. But when I click on one of the xml items....I need to know how to handle each item seperatly if needed.
 
When you add a menu item in the designer, you double-click it to generate a Click event handler, right? That event handler is just a method, like any other, with a Handles clause on it to indicate that it handles the Click event for that menu item.

In this case, you need to write that method yourself and it won't have a Handles clause, because there's no menu item at design time for it to handle an event of. You can write the method by hand but there is an easier way.

Just add a dummy menu item in the designer and double-click it. That will generate the Click event handler. Now, delete the menu item from the designer. That will remove the Handles clause but leave the method behind. You can now change the name of the method to something more appropriate. That method name goes where I've used 'MenuClickEventHandler' in my example.

In the event handler, as with all event handlers, you get access to the object that raised the event via the 'sender' parameter.
 
I don't understand how the custom event knows when the item is clicked.
The event handler method is assigned the event with AddHandler statement.
 
Normally, when you want to handle an event of an object created at run time, you use an AddHandler statement in your own code. The Addhandler statement requires you to specify the event to handle and the AddressOf the method that will handle it. In this case, you pass the AddressOf the method to the ToolStripMenuItem constructor and it will execute the AddHandler statement internally. Hanling the Click event of a dynamically created menu item is such a common operation, they decided to give you a simple way to do it. Don't fight it. ;)
 
Back
Top