Search code examples
c#winformsvisual-studio-2010menustrip

Add ToolMenuStripItem to MenuStrip at specific item?


I am using WinForms, i have tried TreeView and it almost have similar structure to the MenuStrip, only one thing i can't figure out is how to insert a ToolStripMenuItem as a sub item. Is there anyway maybe like:

//There is no Items.Add() after you find the toolstripitem array
MenuStrip.Items.Find("key").Items.Add().
//Same thing
ToolStripMenuItem.Items.Find("key").Items.Add().

I have tried almost everything and there is nothing like that at all, maybe someone could help me.


Solution

  • Try this code.

            var item = menuStrip1.Items["toolStripMenuItem1"];
    
            ToolStripMenuItem newItem = new ToolStripMenuItem("my new item");
            var index = menuStrip1.Items.IndexOf(item);
            menuStrip1.Items.Insert(index + 1, newItem);
    

    Edit: Updated with new code.

    Edit2: This code will add the new menu item inside as dropdown item.

            ToolStripMenuItem item = (ToolStripMenuItem)menuStrip1.Items["toolStripMenuItem1"];
    
            ToolStripMenuItem newItem = new ToolStripMenuItem("my new item");
            item.DropDownItems.Add(newItem);