0
votes

I have a little project in C#, (Windows Forms Application). I have on the form 77 PictureBoxes (pictureBox1, pictureBox2, pictureBox3, ...) and I want to control them but from a new class (Access.cs), by declaring a new one picturebox in the class to control all the pictures.

Because it would be too long if I pass through each pictureBox and add a click method and Copy + Paste the code and change the pictureBox number each time.

I've set the pictures as public and tried the following code:

Access.cs:

using System.Windows.Forms;

public class Access
{
    PictureBox picBox = new PictureBox();

    public void PictureClicked()
    {
        picBox.Image = Properties.Resources.apple;
    }
}

Form1.cs:

private void pictureBox1_Click(object sender, EventArgs e)
{
    Access ac = new Access();
    ac.PictureClicked();
}

but the code didn't work!!

2
And what happened when you tried that code? On a side note, why so many boxes? Do you really need all of them? - Shadow Wizard Is Vaccinated V3
Why can't you just cast the sender object and send that as a parameter to your PictureClicked method? - Toon Casteele
the code didn't work .. unfortunately yes!! - John
You don't need the PictureBox that is declared inside class Access. Just add some code to iterate over your controls and wire up the Click() event of all the found PictureBoxes to the event inside your class. @SATSON showed how to use the "sender" parameter to determine which control fired the event. - Idle_Mind

2 Answers

3
votes

I dont really get what you want to do but you could try to send the object to your Access class:

private void pictureBox1_Click(object sender, EventArgs e)
{
    Access ac = new Access();
    ac.PictureClicked(sender);
}


 public void PictureClicked(Object Sender)
{
           picBox = (PictureBox)Sender;
           picBox.Image = Properties.Resources.apple;
 }
1
votes

Access.Cs

 public void pictureBox1_Click(object sender, EventArgs e)
        {
            PictureBox pi = (PictureBox)sender;

            pi.Image = Properties.Resources.alert__2_;
        }

Form1.Cs

 private void pictureBox2_Click(object sender, EventArgs e)
        {
            Form1 c =new Form1();
            c.pictureBox1_Click(sender, e);


        }

Here pictureBox2_Click this event for all picturebox