I'm having a hard time with choosing random PictureBox out of 20 of it...
I want to make code that will choose 2 random PictureBox and set the same image for both of them, and should repeat that function 5 times...
I've tried using an array but there I got an error that says that pictureBox1 cant be transformed into an array.
string[] array1 = new string[]
{
pictureBox1,
};
CodePudding user response:
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!