0

我正在尝试从包含图像的文件夹中动态创建图片框,但在我的代码中我只能创建一个图片框。如何为每张图片创建一个图片框?

这是我的代码:

 namespace LoadImagesFromFolder
 {
   public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string[] images = Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
        foreach (string image in images)
        {
            pictureBox1.Image = new Bitmap(image); 

        }
    }
}
}
4

2 回答 2

2

您只是为单个 PictureBox ( pictureBox1) 重写图像值,但您需要为每张图片创建一个新的 PictureBox 并设置其值。这样做,你会没事的。

像这样的东西(只是一个例子,根据您的需要修改它!)

foreach (string image in images)
{
   PictureBox picture = new PictureBox();
   picture.Image = new Bitmap(image); 
   someParentControl.Controls.Add(picture);
}
于 2013-02-22T15:31:36.263 回答
1

您必须使用对话框来选择文件,PictureBox在循环中动态创建控件foreach并将它们添加到表单(或其他容器控件)的Controls集合中。

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog d = new OpenFileDialog();

    // allow multiple selection
    d.Multiselect = true;

    // filter the desired file types
    d.Filter = "JPG |*.jpg|PNG|*.png|BMP|*.bmp";

    // show the dialog and check if the selection was made
    if (d.ShowDialog() == DialogResult.OK)
    {
        foreach (string image in d.FileNames)
        {
            // create a new control
            PictureBox pb = new PictureBox();

            // assign the image
            pb.Image = new Bitmap(image);

            // stretch the image
            pb.SizeMode = PictureBoxSizeMode.StretchImage;

            // set the size of the picture box
            pb.Height = pb.Image.Height/10;
            pb.Width = pb.Image.Width/10;

            // add the control to the container
            flowLayoutPanel1.Controls.Add(pb);
        }
    }
}
于 2013-02-22T15:31:37.670 回答