Get a Windows Forms control by name in C#

后端 未结 14 1694
野性不改
野性不改 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:48

    Since you're generating them dynamically, keep a map between a string and the menu item, that will allow fast retrieval.

    // in class scope
    private readonly Dictionary _menuItemsByName = new Dictionary();
    
    // in your method creating items
    ToolStripMenuItem createdItem = ...
    _menuItemsByName.Add("", createdItem);
    
    // to access it
    ToolStripMenuItem menuItem = _menuItemsByName[""];
    

提交回复
热议问题