Click to See Complete Forum and Search --> : Context Menu (submenu) question
binayak
October 26th, 2004, 10:40 AM
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
}
}
RaviGubbi
October 26th, 2004, 03:59 PM
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
}
binayak
October 26th, 2004, 04:10 PM
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);
Norfy
October 27th, 2004, 02:21 AM
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...
binayak
October 27th, 2004, 10:01 AM
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
Norfy
October 27th, 2004, 10:08 AM
MenuItem menuItem = sender as MenuItem;
binayak
October 27th, 2004, 10:09 AM
Thanks dude!
Norfy
October 27th, 2004, 10:26 AM
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();
}
}
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.