C# why can't I get menu items with sub menu items in ToolStripMenuItem?

643 Views Asked by At

Want to create menus and submenus (which has also events on click) but cant figure out how to insert in DropDownItems already created object? When I insert commented code - get always just on last menu all subitems, other don't have it.

    private System.Windows.Forms.ToolStripDropDownButton tlsDropDown;

    List<ToolStripMenuItem> ToolStripListForInsert = new List<ToolStripMenuItem>() 
    {
        new ToolStripMenuItem("Erase"), new ToolStripMenuItem("Change"), new ToolStripMenuItem("NewChange")
    };

    for (int i = 0; i < 10; i++)
    {
        tlsDropDown.DropDownItems.Add(new ToolStripMenuItem("NewItem", null, new ToolStripMenuItem("Erase"), new ToolStripMenuItem("Change"), new ToolStripMenuItem("NewChange")));

        // why this don't work - for all menu items --- work only for last one
        /*tlsDropDown.DropDownItems.Add(new ToolStripMenuItem(names[i], null, ToolStripListForInsert.ToArray()));*/
    }
1

There are 1 best solutions below

0
On

As somebody has already mentioned, you cannot add the same instance of ToolStripItem to multiple (sub-)menus.

You can make your code work by creating new instances of ToolStripItem for each of your parent items.

This for example, should work:

private System.Windows.Forms.ToolStripDropDownButton tlsDropDown;

for (int i = 0; i < 10; i++)
{
    //tlsDropDown.DropDownItems.Add(new ToolStripMenuItem("NewItem", null, new ToolStripMenuItem("Erase"), new ToolStripMenuItem("Change"), new ToolStripMenuItem("NewChange")));

    List<ToolStripMenuItem> ToolStripListForInsert = new List<ToolStripMenuItem>() 
    {
        new ToolStripMenuItem("Erase"), new ToolStripMenuItem("Change"), new ToolStripMenuItem("NewChange")
    };

    tlsDropDown.DropDownItems.Add(new ToolStripMenuItem(names[i], null, ToolStripListForInsert.ToArray()));
}