11

Let's say I have a WinForm that has a menu strip in it. Let's say one of the items of this menu strip is named Cars.

Whenever I open my WinForm, I want to add a subitem under Cars for every car in a table.

Is this possible to do with code?

sooprise
  • 22,657
  • 67
  • 188
  • 276

1 Answers1

18
string[] cars = new string[]{"Volvo", "SAAB"};

foreach (var car in cars)
{
    ToolStripItem subItem = new ToolStripMenuItem(car);
    carsToolStripMenuItem.DropDownItems.Add(subItem);
}

Note: If you add an event to the subItem, make sure you unsubscribe to that event if you are refreshing the list repeatedly, otherwise you will have a memory leak.

Note2: If you have many items you should use DropDownItems.AddRange instead for performance reasons.

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
  • 2
    For some reason, DropDownItems isn't an available option from intellitext... Any ideas? – sooprise Sep 03 '10 at 13:46
  • @Soo, what type is your Cars menu item? When I create a menu in the designer my Cars menu is a ToolStripMenuItem. – Albin Sunnanbo Sep 03 '10 at 19:30
  • 2
    See also here for examples on wiring up events https://stackoverflow.com/questions/1608102/how-to-add-things-to-a-menustrip-programatically – Matthew Lock Jun 15 '17 at 01:04