Get a Windows Forms control by name in C#

后端 未结 14 1524
野性不改
野性不改 2020-11-22 09:22

I have a ToolStripMenuItem called myMenu. How can I access this like so:

/* Normally, I would do: */
this.myMenu... etc.

/* But ho         


        
14条回答
  •  情深已故
    2020-11-22 09:59

    Assuming you have the menuStrip object and the menu is only one level deep, use:

    ToolStripMenuItem item = menuStrip.Items
        .OfType()
        .SelectMany(it => it.DropDownItems.OfType())
        .SingleOrDefault(n => n.Name == "MyMenu");
    

    For deeper menu levels add more SelectMany operators in the statement.

    if you want to search all menu items in the strip then use

    ToolStripMenuItem item = menuStrip.Items
        .Find("MyMenu",true)
        .OfType()
        .Single();
    

    However, make sure each menu has a different name to avoid exception thrown by key duplicates.

    To avoid exceptions you could use FirstOrDefault instead of SingleOrDefault / Single, or just return a sequence if you might have Name duplicates.

提交回复
热议问题