0

I have many images (PictureBoxes) on my form and after clicking them there are operations, like showing image and disabling it from clicking. If I click on PictureBox1, it shows image in that box, same goes for the rest of my boxes. So basically these are the same operations, the only difference is the number inside, like PictureBox16 has number = 16, so that I can show image16 in that box.

Right now, I'm having 24 of these boxes, and every of them has unique function having nearly 100 lines of code - meaning there are 2400 lines, while it could be 100. That's ridiculous. In HTML and JS, I would target these boxes by the same class, and function would read "this.id", so I can know which exactly element was clicked. How can I achieve something like this in C# WFA?

Additionally, I want to change image and enable picture boxes all at once. Right now it's just like this:

PictureBox1.Image = Properties.Resources.img1; PictureBox1.Enabled = true;
...
PictureBox24.Image = Properties.Resources.img24; PictureBox24.Enabled = true;

Is there any option to do it with something like for loop, and transfer value of "i" to target specific PictureBox?

Thanks in advance for any advice.

EDIT I changed the code to something like this:

for (int i = 0; i < 12; i++)
{
     Control myImg = this.Controls["PictureBox" + i];

     if (myImg != null)
     {
         myImg.Image = Properties.Resources.imgName;
         myImg.Enabled = true;
     }    
 }

But "Image" after "myImg" is underlined and I get the following error:

CS1061 'Control' does not contain a definition for 'Image' and no extension method 'Image' accepting a first argument of type 'Control' could be found (are you missing a using directive or an assembly reference?)

which is weird, because this instructions works fine

PictureBox1.Image = Properties.Resources.img1;

Any ideas why do I get such an error?

Marwol
  • 1
  • 2
  • also check this one: [Enable at runtime a series of serially named Label controls using c#](https://stackoverflow.com/questions/37681997/enable-at-runtime-a-series-of-serially-named-label-controls-using-c-sharp) – ASh Aug 17 '17 at 10:11
  • and also this shows loading resource image by name: [How to retrieve Image from Resources folder of the project in C#](https://stackoverflow.com/questions/598484/how-to-retrieve-image-from-resources-folder-of-the-project-in-c-sharp) – ASh Aug 17 '17 at 10:22
  • Hey, please check my edit, this solution doesn't solve everything for me – Marwol Oct 01 '17 at 11:39
  • `PictureBox` is a control derived from `Control` class and adds more properties, like Image. you need a type cast to access those properties: `PictureBox myImg = (PictureBox)this.Controls["PictureBox" + i];` – ASh Oct 01 '17 at 18:15
  • Thanks! Everything working as I wanted. Too bad I can't vote yet :) – Marwol Oct 04 '17 at 15:26

0 Answers0