我在名为“1.png”、“2.png”的资源中有 100 个文件。我有一个PictureBox[]
用代码生成的数组,我想设置array[i].Image = string.Format("Properties.Resources.{0}.png", i);
但这不起作用。
做这个的最好方式是什么?
如果您的图像的名称符合资源文件中的某些模式(例如“Image1”、“Image2”等),您可以通过它们的名称加载它们:
ResourceManager rm = Resources.ResourceManager;
array[i].Image = (Bitmap)rm.GetObject(string.Format("Image{0}", i));
你需要使用反射,像下面这样的东西可以完成任务:
var properties = typeof(Properties.Resources).GetProperties
(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
PictureBox[] array = new PictureBox[100];
int counter = 0;
foreach (PropertyInfo property in properties)
{
var image = property.GetValue(null, null) as System.Drawing.Bitmap;
if (image != null && counter < array.Length)
{
array[counter] = new PictureBox();
array[counter++].Image = image;
}
}
记得using System.Reflection;
在顶部包含。
namespace your_name_project
{
public partial class Form_Begin : Form
{
PictureBox[] pictureBoxs = new PictureBox[6];
public Form_Begin()
{
InitializeComponent();
pictureBoxs[0] = pictureBox1; pictureBoxs[1] = pictureBox2; pictureBoxs[2] = pictureBox3;
pictureBoxs[3] = pictureBox4; pictureBoxs[4] = pictureBox5; pictureBoxs[5] = pictureBox6;
}
//continue
List<PictureBox> pictureBoxes = new List<PictureBox>();
private void buttonX1_Click(object sender, EventArgs e)
{
for (int i = 0; i <3; i++)
{
pictureBoxs[i].Image =your_name_project.Properties.Resources.image_1;// load image1 and Image_2from resource in property of picturebox
}
for (int i = 3; i < 6; i++)
{
pictureBoxs[i].Image = your_name_project.Properties.Resources.Image_2;
}
}
}
}