0

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()));*/
    }
Monish Koyott
  • 374
  • 1
  • 4
  • 20
Ivan Pericic
  • 522
  • 1
  • 8
  • 24
  • 1
    This code look a little confusing. Try to post an [mcve]. And `ToolStirpMenuItem`s can always only be in a single menu at a time. You cannot insert the same instance of an menu item into multiple menus at once. That's because they have to know their parent. So when you added them to the last, they are removed from the previous one. – René Vogt Dec 21 '17 at 12:35
  • Exactly, the ToArray() inside the foreach() looks very fishy. – H H Dec 21 '17 at 12:38
  • 1
    To solve this you can either create individual items for all your menus or try to add them dynamically to the menu where they are needed . – René Vogt Dec 21 '17 at 12:40
  • @RenéVogt - might will now be more clear – Ivan Pericic Dec 21 '17 at 12:40
  • 2
    Well as I said: when you add an instance of a `ToolStripItem` to a menu, it is removed from its former parent menu. You cannot add the same instance to multiple (sub-)menus. – René Vogt Dec 21 '17 at 12:45

1 Answers1

1

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()));
}
sachin
  • 2,341
  • 12
  • 24