Programmatically Adding Items To A Menu Strip?

sooprise picture sooprise · Sep 2, 2010 · Viewed 19.6k times · Source

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?

Answer

Albin Sunnanbo picture Albin Sunnanbo · Sep 2, 2010
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.