In your constructor create and set a local Dictionary<string, PictureBox>
. Remember, Forms are classes just like any other C# class and should be treated as such.
Instead of for
, you can now use foreach
and access the .Key
and .Value
to get the file names and PictureBox
objects. This only works because you have such a rigid relationship between PictureBox
name and desired picture, however. If the pairing changes, or you ever want to use the same image for two pictures boxes you'd want to change this to a List<Tuple<string, PictureBox>>
. That may even be the best want to handle the situation, in fact.
public class Form1 : Form
{
private Dictionary<string, PictureBox> pictureBoxes;
public Form1()
{
pictureBoxes = new Dictionary<string, PictureBox>()
{
{"Pictures\\green.png", pictureBox_D},
{"Pictures\\blue.png", pictureBox_B},
// Etcetera
}
}
}
When you want to loop over them you do the following:
foreach(var kvp in pictureBoxes)
{
kvp.Value.Image = new Bitmap(kvp.Key);
}