none
100+ Pictureboxes, All with the same function, do I have to type it 100+ times?

    Question

  • I have many pictureboxes and I need to do the same thing when I click on all of them.  Is there any way to do it so it's all at once?  Or, better yet, put their event handlers in another class/file?  Thanks, new to VS/C#.
    Monday, March 03, 2008 7:05 PM

Answers

  • Use a single event handler:

     

    Code Snippet

    for (int i = 1; i <= 100; i++)

        ((PictureBox)Controls["pictureBox" + i]).Click += My_pictureBoxClick;

     

     

     

    Code Snippet

    void My_pictureBoxClick(object sender, EventArgs e)

    {

        PictureBox pictureBox = sender as PictureBox;

        // do something with it

    }

     

     

     

     

    Monday, March 03, 2008 8:25 PM

All replies

  • You can use a for loop for that or have a function which processes picturebox and pass your pictureboxes to it.
    Monday, March 03, 2008 7:18 PM
  • Please post the code, as I too have some questions only regarding the .Text of my labels from 1 to 48.

    I want to place 1 if like:

    if (this.Label1 to 48.text=numIdea)
    {
    This.labelX.BackColor.Blue
    }
    Monday, March 03, 2008 7:40 PM
  • Use a single event handler:

     

    Code Snippet

    for (int i = 1; i <= 100; i++)

        ((PictureBox)Controls["pictureBox" + i]).Click += My_pictureBoxClick;

     

     

     

    Code Snippet

    void My_pictureBoxClick(object sender, EventArgs e)

    {

        PictureBox pictureBox = sender as PictureBox;

        // do something with it

    }

     

     

     

     

    Monday, March 03, 2008 8:25 PM