Choosing random picturebox out of 20 of them c#

Viewed 69

I'm having a hard time with choosing a random PictureBox.

I want to choose 2 random PictureBox and set the same image for both of them. The function should repeat 5 times.

I've tried using an array, but I received an error that says that pictureBox1 can't be transformed into an array.

string[] array1 = new string[]
{
    pictureBox1,
};
1 Answers

Lets say you have an list of PictureBoxes. Like so:

var picList = new List<PictureBox>();

And you fill the list with PictureBox Controls.

picList.Add(pictureBox1)
picList.Add(pictureBox2)
picList.Add(pictureBox3)
//etc

And you want to pick at random, a picture box from the list. You can just use the Next function of the Random class to generate you a number between 0 and the size of the list.

For example, first declare your random class at the class level scope:

static Random rnd = new Random();

Then, within your function, when you want to generate a random number use the Next function, like so.

randomNum = rnd.Next(0, picList.Count);  

Once you have your number, you can set the image to whatever you want. Repeat that a 2nd time for the 2nd PictureBox. For example:

var picBox = picList[randomNum];
picBox.Image = ?? // set image here!
Related