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

荒凉一梦 提交于 2020-06-12 05:48:25

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/13721627/how-to-add-sub-items-to-a-menustrips-toolstripmenuitem-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!