Search code examples
c#imagewinformsforeachpicturebox

Using a foreach loop with pictureboxes


I am trying to make my code as short as possible and I intend on randomising images from a choice of 6 pictures for 3 different picture boxes at certain intervals. Instead of copy and pasting the switch and case three times for each picturebox, I am trying to instead change in one foreach loop. I am very new to C# and windows forms so any help is appreciated. EDIT:Sorry for poor wording, but the problem was that the program says element is not a valid picturebox and I am wondering why and how to fix it if possible, but thanks for the alternate solutions.

private void timer1_Tick(object sender, EventArgs e)
    {

        Random random = new Random();
        int picture = random.Next(1, 7);
        var pictures = new List<PictureBox> { pictureBox1, pictureBox2, pictureBox2 };
        foreach (PictureBox element in pictures)
        {
            switch (picture)
            {
                case 1:
                    this.element.Image = Image.FromFile("C:\\Users\\seanb\\OneDrive\\Pictures\\cherry.jpg");
                    break;
                case 2:
                    this.element.Image = Image.FromFile("C:\\Users\\seanb\\OneDrive\\Pictures\\bell.jpg");
                    break;
                case 3:
                    this.element.Image = Image.FromFile("C:\\Users\\seanb\\OneDrive\\Pictures\\lemon.jpg");
                    break;
                case 4:
                    this.element.Image = Image.FromFile("C:\\Users\\seanb\\OneDrive\\Pictures\\orange.jpg");
                    break;
                case 5:
                    this.element.Image = Image.FromFile("C:\\Users\\seanb\\OneDrive\\Pictures\\star.jpg");
                    break;
                case 6:
                    this.element.Image = Image.FromFile("C:\\Users\\seanb\\OneDrive\\Pictures\\skull.jpg");
                    break;
            }
        }

Solution

  • What about using a Dictionary like this:

    Dictionary<int, Image> dictionary = new Dictionary<int, Image>()
    {
        {1,  Image.FromFile("C:\\Users\\seanb\\OneDrive\\Pictures\\cherry.jpg")},
        {2,  Image.FromFile("C:\\Users\\seanb\\OneDrive\\Pictures\\bell.jpg")},
    };
    
    dictionary.TryGetValue(picture, out value);
    if (value != null)
    {
        this.element.Image = value;
    }