How to Add Sub Items to a MenuStrip's ToolStripMenuItem in C#
Asked Answered
H

1

5

I have added a menustrip1 into my windows form and I statically added one toolstripmenuitem (WindowstoolStripmenuItem) to that menustrip1. And I have created a toolstripmenuitem dynamically. I want to add this dynamic toolstripmenuitem to the static menustripitem(WindowstoolStripmenuItem) which is created statically on design time.

ToolStripMenuItem itm = new ToolStripMenuItem();
itm.Name = "fm1";
itm.Text = "Form1";

How can I add this subitem to the static menustrip's Windows item.

Horripilate answered 5/12, 2012 at 10:56 Comment(0)
N
17

You can add a ToolStripMenuItem to another ToolStripMenuItem.DropDownItems collection.

If you don't have a reference to your ToolStripMenuItem, you can get one by key (Name Property) or Index

var itm = menustrip1.Items["Text"];
var itm = menustrip1.Items[0];

Here is the code

var menustrip1 = new System.Windows.Forms.MenuStrip();
var item = new System.Windows.Forms.ToolStripMenuItem()
{
    Name = "Test",
    Text = "Test" 
};
var item2 = new System.Windows.Forms.ToolStripMenuItem()
{
    Name = "Test",
    Text = "Test"
};
item.DropDownItems.Add(item2);
menustrip1.Items.Add(item);
Nereid answered 5/12, 2012 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.