Holy Goat
Holy Goat

Reputation: 31

Using a 'for' loop in C# to fill picturebox number 'i' with an image

I have six Pictureboxes and a for loop. I'd like to refer to PictureBox with the same number as 'i' variable that's being incremented inside a for loop.

For example, if the 'i' variable from my for loop is 2 I'd like to assign an image to picturebox2.

How do I do this the easiest way? It is a unique way that also works for other controls (that is, labels, textboxes) would be nice. :)

Upvotes: 3

Views: 11740

Answers (3)

Hossein Moradinia
Hossein Moradinia

Reputation: 6244

I implement this with Array of PictureBoxes :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ImageChanger
{
    public partial class Form1 : Form
    {
        PictureBox[] pictureBoxs=new PictureBox[4];

        public Form1()
        {
            InitializeComponent();


            pictureBoxs[0] = pictureBox1;
            pictureBoxs[1] = pictureBox2;
            pictureBoxs[2] = pictureBox3;
            pictureBoxs[3] = pictureBox4;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 4; i++)
            {
                // Load Image from Resources
                pictureBoxs[i].Image = Properties.Resources.img100;

                Application.DoEvents();
                Thread.Sleep(1000);
            }
        }


    }
}

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

You can use Tag property of any control to provide additional info (like image name or index). E.g. you can provide index for your pictureBoxes. Also use ImageList to store list of images:

foreach(var pictureBox in Controls.OfType<PictureBox>())
{
    if (pictureBox.Tag == null) // you can skip other pictureBoxes
        continue;

    int imageIndex = (int)pictureBox.Tag;
    pictureBox.Image = imageList.Images[imageIndex];
}

Also you can search picture box by tag value:

var pictureBox = Controls.OfType<PictureBox>()
                         .FirstOrDefault(pb => (int)pb.Tag == index);

Another option - if all your pictureBoxes have names like pictureBox{index}. In this case you can go without usage of Tag:

var pictureBox = Controls
  .OfType<PictureBox>()                     
  .FirstOrDefault(pb => Int32.Parse(pb.Name.Replace("pictureBox", "")) == index);

Upvotes: 2

Guffa
Guffa

Reputation: 700830

Put references to the controls in an array:

PictureBox[] boxes = {
  PictureBox1, PictureBox2, PictureBox3, PictureBox4, PictureBox5, PictureBox6
};

Then you can loop through them:

for (int i = 0; i < boxes.Length; i++) {
  // use boxes[i] to access each picture box
}

Upvotes: 4

Related Questions