Get a Windows Forms control by name in C#

后端 未结 14 1701
野性不改
野性不改 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 10:05

    Assuming you have Windows.Form Form1 as the parent form which owns the menu you've created. One of the form's attributes is named .Menu. If the menu was created programmatically, it should be the same, and it would be recognized as a menu and placed in the Menu attribute of the Form.

    In this case, I had a main menu called File. A sub menu, called a MenuItem under File contained the tag Open and was named menu_File_Open. The following worked. Assuming you

    // So you don't have to fully reference the objects.
    using System.Windows.Forms;
    
    // More stuff before the real code line, but irrelevant to this discussion.
    
    MenuItem my_menuItem = (MenuItem)Form1.Menu.MenuItems["menu_File_Open"];
    
    // Now you can do what you like with my_menuItem;
    

提交回复
热议问题