Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add sub menu items in contextmenustrip using C#4.0?

I have one contextmenustrip control associated with treenode. I have created one menu item in contextmenustrip manually in the form itself(for example named as "Assign").

Now I want to add sub menu items whenever user clicks this Assign item, it will create a list of users name as a sub menu item with checked or unchecked option.

For example, once user clicked Assign then I want to show the user name dynamically.

like image 278
Saravanan Avatar asked May 03 '11 10:05

Saravanan


People also ask

How do I install ContextMenuStrip?

Drag and drop or double click on a ControlMenuStrip control to add it to the form. Add the menu items, Cut, Copy and Paste to it. Add a RichTextBox control on the form. Set the ContextMenuStrip property of the rich text box to ContextMenuStrip1 using the properties window.


2 Answers

To add an item, you would call

myContextMenuStrip.Items.Add("Item title", null, myClickHandler); 

To add a sub-menu, you take an existing item and do the same to it:

(myContextMenuStrip.Items[0] as ToolStripMenuItem).DropDownItems.Add(...) 
like image 62
Roman Starkov Avatar answered Oct 14 '22 22:10

Roman Starkov


Define your menu strip and items

ContextMenuStrip menu = new ContextMenuStrip(); ToolStripMenuItem item, submenu; 

Create new item.

submenu = new ToolStripMenuItem(); submenu.Text = "Sub-menu 1"; 

At this time your new item is just like others. Now create several new items and add them to submenu:

item = new ToolStripMenuItem(); item.Text = "Sub-item 1"; submenu.DropDownItems.Add(item);  item = new ToolStripMenuItem(); item.Text = "Sub-item 2"; submenu.DropDownItems.Add(item); 

At last add sub-menu to your main ContextMenuStrip

menu.Items.Add(submenu); 
like image 25
Kamarado Avatar answered Oct 14 '22 23:10

Kamarado