简体   繁体   中英

Making an array of pictureboxes, each with different images

I have 100 files in Resources named "1.png", "2.png". I have a PictureBox[] array generated with code, and I want to set array[i].Image = string.Format("Properties.Resources.{0}.png", i); But this does not work.

What is the best way to do this?

If your images have names that conform to some pattern inside the resource file (like "Image1", "Image2", etc.), you may load them by their names:

ResourceManager rm = Resources.ResourceManager;
array[i].Image = (Bitmap)rm.GetObject(string.Format("Image{0}", i));

you can refer to this post.

or you can simply use :

array[i].Image = Properties.Resources.img1 

You need to use Reflection, Something like following would do the task:

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;
    }
}

Remember to include using System.Reflection; at the top.

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;
                }
            } 
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM