Get a Windows Forms control by name in C#

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

    A simple solution would be to iterate through the Controls list in a foreach loop. Something like this:

    foreach (Control child in Controls)
    {
        // Code that executes for each control.
    }
    

    So now you have your iterator, child, which is of type Control. Now do what you will with that, personally I found this in a project I did a while ago in which it added an event for this control, like this:

    child.MouseDown += new MouseEventHandler(dragDown);
    
    0 讨论(0)
  • 2020-11-22 10:13
    Control GetControlByName(string Name)
    {
        foreach(Control c in this.Controls)
            if(c.Name == Name)
                return c;
    
        return null;
    }
    

    Disregard this, I reinvent wheels.

    0 讨论(0)
提交回复
热议问题