bwoogie
bwoogie

Reputation: 4427

Finding and Creating Sub Menus Dynamically

I have a ToolStripMenuItem I need to check if it has a sub menu with a particular name, if it exists, add a new menu item to that sub menu, and if not, create the sub menu and add the item to the new sub menu.

ToolStripItemCollection menu = tsmi1.DropDownItems;
                for(int i = 0; i < menu.Count; i++) {
                    if(item.Category.Equals(menu[i].Text)) {
                        menu[i]. //need to add new menu item here....
                    }
                }

It may just be that I don't understand how the menu system actually works, but it appears I can't add an item to my menu object.

Upvotes: 0

Views: 278

Answers (1)

Ann L.
Ann L.

Reputation: 13965

Is your sub-menu a ToolStripDropDownItem?

The objects in TooLStripItemCollection are all of type ToolStripItem. You may need to cast the item you find to the derived class, ToolStripDropDownItem.

That will give you access to its DropDownItems collection, which is another ToolStripItemCollection and has Add, AddRange, and Insert methods.

I haven't worked with ToolStripDropDownItem myself, but that's the path I'd start on.


Edit by bwoogie: Final code:

ToolStripMenuItem tsmi = new ToolStripMenuItem();
tsmi.Text = item.Name;
tsmi.Click += node_Click;

ToolStripItemCollection nodeMenu = nodesToolStripMenuItem.DropDownItems;
for (int i = 0; i < nodeMenu.Count; i++) {
    if (item.Category.Equals(nodeMenu[i].Text)) {
        ((ToolStripMenuItem)nodeMenu[i]).DropDownItems.Add(tsmi);
    } else {
        ToolStripItem newtsi = nodeMenu.Add(item.Category);
        ((ToolStripMenuItem)newtsi).DropDownItems.Add(tsmi);
    }
}

Upvotes: 1

Related Questions