我有一个包含10个图片框的简单表单,如:pictureBox1
,pictureBox2
,pictureBox3
...
我有一个包含10张图片的文件夹,例如:image1
,image2
,image3
...
现在我足够聪明,知道我不想硬编码pictureBox1.ImageLocation = image1
,pictureBox2.ImageLocation = image2
...相反,我需要创建某种循环或数组来填充我的图片带有各自图像的盒子,但我不够聪明,无法弄清楚如何。
类似的东西:
for (int i = 0; i < 10; i++)
{
pictureBox[i].ImageLocation = image[i];
}
最终,我希望这个项目能够动态扩展,如果我有一个12个图像的文件,程序将只创建12个图片框并加载图像。一点帮助就会很棒。
答案 0 :(得分:0)
虽然我建议列表,但你在那里会有粗暴的工作。
List<PictureBox> pictureBoxes = new List<PictureBox>();
List<Image> images = new List<Image>();
//code to populate your lists
for (int i = 0; i < pictureBoxes.Count; i++)
{
pictureBoxes[i].Image = images[i];
}
如果您想确保自己的PictureBox
列表中有足够的图片,可以提前检查:
if (images.Count >= pictureBoxes.Count)
{
for (int i = 0; i < pictureBoxes.Count; i++)
{
pictureBoxes[i].Image = images[i];
}
}
...或在用完图像之前尽可能多地填写。
for (int i = 0; i < pictureBoxes.Count && i < images.Count; i++)
{
pictureBoxes[i].Image = images[i];
}
<小时/> 编辑: 因此,如果您想使用字符串来设置图像的位置,那么您可以这样做。看看这个:
List<PictureBox> pictureBoxes = new List<PictureBox>();
List<string> imageLocations = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
PictureBox PB1 = new PictureBox();
PB1.Location = new Point(0, 0);
PB1.Size = new Size(144, 197);
Controls.Add(PB1);
PictureBox PB2 = new PictureBox();
PB2.Location = new Point(145, 0);
PB2.Size = new Size(327, 250);
Controls.Add(PB2);
pictureBoxes.Add(PB1);
pictureBoxes.Add(PB2);
imageLocations.Add(@"C:\PicExample\image1.jpg");
imageLocations.Add(@"C:\PicExample\image2.jpg");
for (int i = 0; i < pictureBoxes.Count && i < imageLocations.Count; i++)
{
pictureBoxes[i].ImageLocation = imageLocations[i];
}
}
<小时/> 编辑迭代创建
PictureBoxe
列表:
如果您不想担心硬编码列表(并且您的图片框大小相同),您可以执行以下操作:
for (int i = 0; i < HoweverManyPictureBoxesYouWant; i++)
{
PictureBox PB = new PictureBox();
PB.Name = "PB" + i.ToString();
PB.Location = new Point(250 * i, 0); //Edit this as you see fit for location, i'm just putting them in a row
PB.Size = new Size(250, 250);
PB.ImageLocation = @"C:\PicExample\image" + i.ToString() + ".jpg";
Controls.Add(PB);
pictureBoxes.Add(PB); //You only need to do this if you want the PB's in a list for other reasons than setting the image location
}