1

我在名为“1.png”、“2.png”的资源中有 100 个文件。我有一个PictureBox[]用代码生成的数组,我想设置array[i].Image = string.Format("Properties.Resources.{0}.png", i);但这不起作用。

做这个的最好方式是什么?

4

4 回答 4

3

如果您的图像的名称符合资源文件中的某些模式(例如“Image1”、“Image2”等),您可以通过它们的名称加载它们:

ResourceManager rm = Resources.ResourceManager;
array[i].Image = (Bitmap)rm.GetObject(string.Format("Image{0}", i));
于 2013-05-06T11:45:14.800 回答
2

你可以参考这篇文章。

或者您可以简单地使用:

array[i].Image = Properties.Resources.img1 
于 2013-05-06T11:16:10.350 回答
2

你需要使用反射,像下面这样的东西可以完成任务:

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;在顶部包含。

于 2013-05-06T11:27:55.710 回答
1
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;
                }
            } 
        }
}
于 2016-03-29T19:20:12.830 回答