从 20 个 c# 中选择随机图片框

Choosing random picturebox out of 20 of them c#

我很难随机选择 PictureBox

我想随机选择 2 个 PictureBox 并为它们设置相同的图像。该函数应重复 5 次。

我试过使用数组,但收到一条错误消息,指出无法将 pictureBox1 转换为数组。

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

假设您有一个图片框列表。像这样:

var picList = new List<PictureBox>();

然后用 PictureBox 控件填充列表。

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

并且您想从列表中随机选择一个图片框。您可以只使用 Random class 的 Next 函数来生成一个介于 0 和列表大小之间的数字。

例如,首先在 class 级别范围内声明您的随机 class:

static Random rnd = new Random();

然后,在您的函数中,当您想生成一个随机数时,请使用 Next 函数,就像这样。

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

获得号码后,您可以将图像设置为任何您想要的。对第二个 PictureBox 重复第二次。例如:

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