Reputation: 1003
I'm trying to create pictures boxes dynamically from a folder containing images, but in my code I can only create one picture box. How do I do to create one picture box per image?
Here is my code:
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);
}
}
}
}
Upvotes: 0
Views: 4072
Reputation: 32571
You have to use a dialog to select the files, create the PictureBox
controls dynamically in the foreach
loop and add them to the form's (or other container control's) Controls
collection.
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);
}
}
}
Upvotes: 1
Reputation: 13598
You're just rewriting the image value for your single PictureBox (pictureBox1
), but you need to create a new PictureBox for every picture instead and set its value. Do that and you'll be fine.
Something like this (just an example, modify this to your needs!)
foreach (string image in images)
{
PictureBox picture = new PictureBox();
picture.Image = new Bitmap(image);
someParentControl.Controls.Add(picture);
}
Upvotes: 2