Get a Windows Forms control by name in C#

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

    One of the best way is a single row of code like this:

    In this example we search all PictureBox by name in a form

    PictureBox[] picSample = 
                        (PictureBox)this.Controls.Find(PIC_SAMPLE_NAME, true);
    

    Most important is the second paramenter of find.

    if you are certain that the control name exists you can directly use it:

      PictureBox picSample = 
                            (PictureBox)this.Controls.Find(PIC_SAMPLE_NAME, true)[0];
    

提交回复
热议问题