Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check which submenu item was clicked in context menu strip

There is a ContextMenuStrip in a grid control.

I have named it as GridContextMenu.

The GridContextMenu is populated with 4 - 5 items using the following code :

 gridcontextMenu.Items.Add(new ToolStripMenuItem
                        {
                            Name = Plants,
                            Text = Plants,
                            Tag = Plants,
                            Width = 100,
                            Image = <image source is put here>
                        });

gridcontextMenu.Items.Add(new ToolStripMenuItem
                        {
                            Name = Animals,
                            Text = Animals,
                            Tag = Animals,
                            Width = 100,
                            Image = <image source is put here>
                        });

For the animal menu in tool strip, i added submenu in the following way

(gridcontextMenu.Items[1] as ToolStripMenuItem).DropDownItems.Add("Tiger", image_source, new EventHandler(SubmenuItem_Click));
(gridcontextMenu.Items[1] as ToolStripMenuItem).DropDownItems.Add("Lion", image_source, new EventHandler(SubmenuItem_Click));
(gridcontextMenu.Items[1] as ToolStripMenuItem).DropDownItems.Add("Elephant", image_source, new EventHandler(SubmenuItem_Click));

In the SubmenuItem_Click event handler i need to know which animal submenu was clicked.

How to achieve this ?

currently i have the code for event handler in the following way :

private void SubmenuItem_Click(object sender, EventArgs e)
{
}

How to check condition in this event that which animal submenu was selected ? Kindly share the answer.

like image 930
Vikas Kunte Avatar asked Dec 05 '22 13:12

Vikas Kunte


2 Answers

You can do something like this:

private void SubmenuItem_Click(object sender, EventArgs e)
{
    var clickedMenuItem = sender as MenuItem; 
    var menuText = clickedMenuItem.Text;

    switch(menuText) {
        case "Tiger":
           break;

        case "Lion":
          break;
         . ...
    }
}
like image 125
Tigran Avatar answered Jan 05 '23 00:01

Tigran


You can use Tag for this purpose in case when your should localize your application. Moreover Tag is an object so you can put any tapy of data there. For example Enum type.

private void SubmenuItem_Click(object sender, EventArgs e)
{
    var clickedMenuItem = sender as MenuItem; 
    EnumType item = (EnumType)clickedMenuItem.Tag;

    switch(item) {
        case TigeItem:
           break;
        case LionItem:
          break;
         ...
    }
}
like image 45
Denis Kucherov Avatar answered Jan 04 '23 22:01

Denis Kucherov