0

I want to generate and change the image in the PictureBox array by button click.

Here is what I have tried so far.

public Form1() {
     InitializeComponent();
 }

 PictureBox[] boxes = new PictureBox[6];

 private void GenerateButton1_Click(object sender, EventArgs e) {

     for (int i = 0; i < boxes.Length; i++) {
         boxes[i] = new PictureBox(); //set the pointer to a new PictureBox instance
         if (i == 0) boxes[i].Location = new System.Drawing.Point(3, 3);
         if (i == 1) boxes[i].Location = new System.Drawing.Point(221, 3);
         if (i == 2) boxes[i].Location = new System.Drawing.Point(439, 3);
         if (i == 3) boxes[i].Location = new System.Drawing.Point(3, 210);
         if (i == 4) boxes[i].Location = new System.Drawing.Point(221, 210);
         if (i == 5) boxes[i].Location = new System.Drawing.Point(439, 210);
         boxes[i].Size = new System.Drawing.Size(200, 200);
         boxes[i].Image = Image.FromFile(Application.StartupPath + "\\red.PNG"); //for setting its image

     }

     this.Controls.AddRange(boxes);
 }

 private void button1_Click(object sender, EventArgs e) {

     int i = 3;
     int signal = 1;
     boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;
     if (signal == 0) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\red.PNG");
     if (signal == 1) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\green.PNG");
     if (signal == 2) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\grey.PNG");
 }
 }
 }

by doing button1 click, the image will change from red.PNG to green.PNG or grey.PNG depending on the condition, however, I have to redo the image Properties declaration, for example, boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;. Otherwise the PictureBox lose its properties. Is there any simpler way to do this.

Thank you in advance.

user3837868
  • 917
  • 1
  • 12
  • 24
RojoL3L3
  • 3
  • 4
  • Based on the code shown, it would only lose properties if you're clicking GenerateButton1 multiple times causing new PictureBoxes to be generated (and subsequently any properties you set would be lost). Also, how are `i` and `signal` ever going to change if they're declared inside the button1 handler? – Idle_Mind May 26 '19 at 23:51
  • it is my unit testing, I am just curious on how to preserve the properties efficiently in C# because I am calling the same PictureBox array `boxes` – RojoL3L3 May 27 '19 at 00:40
  • I tested this, and even if I uncomment this line `boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;` it works fine. Are you trying to figure out how to handle if someone presses `Generate` multiple times? – Matt Oestreich May 27 '19 at 00:43
  • Yes, it functions properly, but the image is not stretched anymore. – RojoL3L3 May 27 '19 at 00:46
  • So move `boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;` up into the `GenerateButton1_Click()` method instead? – Idle_Mind May 27 '19 at 00:52

0 Answers0