0

画像を含むフォルダーから画像ボックスを動的に作成しようとしていますが、私のコードでは画像ボックスを 1 つしか作成できません。画像ごとに 1 つの画像ボックスを作成するにはどうすればよいですか?

これが私のコードです:

 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でコントロールを動的に作成して、フォーム (または他のコンテナー コントロール) のコレクションに追加する必要があります。foreachControls

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 に答える