Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Adding Items To A Menu Strip?

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?

like image 684
sooprise Avatar asked Sep 02 '10 20:09

sooprise


People also ask

How do I add items to MenuStrip C#?

We can add items to a MenuStrip at design-time from Properties Window by clicking on Items Collection as you can see in Figure 4. When you click on the Collections, the String Collection Editor window will pop up where you can type strings. Each line added to this collection will become a MenuStrip item.

What is ToolStripMenuItem?

The ToolStripMenuItem class provides properties that enable you to configure the appearance and functionality of a menu item. To display a check mark next to a menu item, use the Checked property.

What is MenuStrip?

MenuStrip is the top-level container that supersedes MainMenu. It also provides key handling and multiple document interface (MDI) features.


1 Answers

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.

like image 152
Albin Sunnanbo Avatar answered Oct 01 '22 15:10

Albin Sunnanbo