有了6个图像名称列表和6个图片框列表,我想随机显示图片框中资源的图像。
此代码无效。只是空的图片框....为什么?
List<PictureBox> box = new List<PictureBox>();
box.Add(pictureBox1);
box.Add(pictureBox2);
box.Add(pictureBox3);
box.Add(pictureBox4);
box.Add(pictureBox5);
box.Add(pictureBox6);
List<string> name = new List<string>();
name.Add("_1.jpg");
name.Add("_2.jpg");
name.Add("_3.jpg");
name.Add("_4.jpg");
name.Add("_5.jpg");
name.Add("_6.jpg");
Random r = new Random();
for (int i = 0; i < box.Count; i++)
{
int rand = r.Next(0, 6);
String imgname = name[rand];
object Ob= Properties.Resources.ResourceManager.GetObject(imgname);
box[i].Image = Ob as Image;
}
答案 0 :(得分:0)
您的资源通常不包含文件扩展名,因此请尝试使用图片名称。
name.Add("_1");
name.Add("_2");
就个人而言,我不会在文件名中包含下划线 - 可能会使事情变得复杂。
答案 1 :(得分:0)
我修改了你的代码:
List<PictureBox> box = new List<PictureBox>();
box.AddRange(new PictureBox[]
{
pictureBox1,
pictureBox2,
pictureBox3,
pictureBox4,
pictureBox5,
pictureBox6,
});
List<string> name = new List<string>()
{
"_1.jpg",
"_2.jpg",
"_3.jpg",
"_4.jpg",
"_5.jpg",
"_6.jpg"
};
Random r = new Random();
for (int i = 0; i < this.Count; i++)
{
var rm = new System.Resources.ResourceManager(((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()).GetName().Name + ".Properties.Resources", ((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()));
this[i].Image = (Bitmap)rm.GetObject(name[r.Next(0, 6)]);
}