Context Menu (submenu) question
Hi,
I am creating a submenu at the runtime and this submenu can have many items (the number is not known at compile time). I want to how to create event handler for these menuitems. Is there a generalized way to handle the events on these submenu items? Please look at the following code and suggest:
public void GetAllHierarchyList(MenuItem mnuFile)
{
mnuFile.MenuItems.Clear();
foreach (HierarchyNode h in this.hierarchy.HierarchieNodes)
{
mnuFile.MenuItems.Add (h.Type); //want event handler for all these
//items
}
}
[599 byte] By [
binayak] at [2007-11-19 1:51:41]

# 1 Re: Context Menu (submenu) question
After adding the menu item
mnuFile.MenuItems.Add (h.Type);
add an event handler
mnuFile.MenuItems.Click += new System.EventHandler(MenuItem_Click);
Add the event handler
private void MenuItem_Click(object sender, EventArgs e)
{
// Add code here
}
# 2 Re: Context Menu (submenu) question
I tried your code but it gives error:
error CS0117: 'System.Windows.Forms.Menu.MenuItemCollection' does not contain a definition for 'Click'
for the line
mnuFile.MenuItems.Click += new System.EventHandler(this.MenuItemAddExisiting_Click);
# 3 Re: Context Menu (submenu) question
RaviGubbi had the right idea. As you've found out MenuItemCollection does not understand Click but MenuItem does. So mnuFile.MenuItems.Add (h.Type, new System.EventHandler(this.MenuItemAddExisting_Click));
OR
MenuItem menuItem = new MenuItem(h.Type);
menuItem.Click += new System.EventHandler(this.MenuItemAddExisting_Click);
mnuFile.MenuItems.Add(menuItem);The next problem you have is deciding what to do when a menuItem is clicked...
Norfy at 2007-11-9 1:43:50 >

# 4 Re: Context Menu (submenu) question
Thanks. Help me out a little more.
How to find out info about the menuitem that's clicked from the handler/
private void MenuItem_Click(object sender, EventArgs e)
{
// Add code here
}
Thanks
# 7 Re: Context Menu (submenu) question
Since I got a thankyou, consider this:foreach (HierarchyNode node in this.hierarchy.HierarchieNodes)
{
// create a handler for each node
MenuItemHandler handler = new MenuItemHandler(node);
// ...and assign it to a menu item
MenuItem menuItem = new MenuItem(node.type);
menuItem.Click += new System.EventHandler(handler.MenuItem_Click);
mnuFile.MenuItems.Add (menuItem);
}
private class MenuItemHandler
{
public MenuItemHandler(HierarchyNode node)
{
// TODO store whatever you need
}
public void MenuItem_Click(object sender, EventArgs e)
{
// Since one-to-one relation ship with menuItem no need to ask who the
// sender is.
DoSomething();
}
}
Norfy at 2007-11-9 1:47:53 >
