John
John

Reputation: 89

Controlling a PictureBox from a class

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!!

Upvotes: 0

Views: 4972

Answers (2)

Sathish
Sathish

Reputation: 4487

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

Upvotes: 1

Johan Nordli
Johan Nordli

Reputation: 1230

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;
 }

Upvotes: 3

Related Questions