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?
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.
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.
MenuStrip is the top-level container that supersedes MainMenu. It also provides key handling and multiple document interface (MDI) features.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With