Boats Boats - 3 months ago 37
C# Question

Loop multiple images through multiple pictureboxes

I would like to display four images at the same time and upon form load the images switch places. Currently, images will appear in different numbers, for example: 1 image will appear or 2 images, etc up 4. I also want to ensure that no duplicates will appear.

Code from Form1_Load:

PictureBox[] boxes = new PictureBox[4];

boxes[0] = pictureBox0;
boxes[1] = pictureBox1;
boxes[2] = pictureBox2;
boxes[3] = pictureBox3;

for (int i = 0; i < boxes.Length; i++)
{
int switcher = r.Next(0, 5);

switch (switcher)
{
case 0:
{ boxes[i].Image = Properties.Resources.dog0; } break;
case 1:
{ boxes[i].Image = Properties.Resources.dog1; } break;
case 2:
{ boxes[i].Image = Properties.Resources.dog2; } break;
case 3:
{ boxes[i].Image = Properties.Resources.dog3; } break;
}
}



enter image description here
Two examples given above as to what currently happens.

Update - Working

The program now moves images around upon Load and there are no duplicates :)

List<Bitmap> resources = new List<Bitmap>();
resources.Add(Properties.Resources.dog0);
resources.Add(Properties.Resources.dog1);
resources.Add(Properties.Resources.dog2);
resources.Add(Properties.Resources.dog3);

for (int i = 0; i < resources.Count; i++)
{
resources = resources.OrderBy(a => Guid.NewGuid()).ToList();

pictureBox0.Image = resources[0];
pictureBox1.Image = resources[1];
pictureBox2.Image = resources[2];
pictureBox3.Image = resources[3];
}


enter image description here
enter image description here

Two example given above showing what happens now that it works.

Answer

As M.kazem Ahkhary points out you need to shuffle the images:

List<Bitmap> resources = new List<Bitmap>();
resources.Add(Properties.Resources.dog0);
resources.Add(Properties.Resources.dog1);
resources.Add(Properties.Resources.dog2);
resources.Add(Properties.Resources.dog3);

resources = resources.OrderBy(a => Guid.NewGuid()).ToList(); // Dirty but effective shuffle method

pictureBox0.Image = resources[0];
pictureBox1.Image = resources[1];
pictureBox2.Image = resources[2];
pictureBox3.Image = resources[3];
Comments