动态生成PictureBox控件,涉及:PictureBox控件和flowLayoutPanel面板

时间:2023-03-09 14:55:46
动态生成PictureBox控件,涉及:PictureBox控件和flowLayoutPanel面板

一、概述

flowLayoutPanel面板是一系列控件的容器,有关详细的使用方法留待以后总结。

二、问题提出

问题提出:点击按钮,扫描指定文件夹并将其中的所有图片放在flowLayoutPanel面板内。换句话说,就是在flowLayoutPanel面板内动态生成N个PictureBox控件。

此外,还有一个要求,N是变化的,有时显示5个图片,有时显示20个图片。这就要求动态生成新的控件之前先销毁已经存在的控件。

三、销毁PictureBox控件

销毁控件代码:

box[v].Dispose();
box[v] = null;
GC.Collect();

四、示例代码

            N = int.Parse(comboBox_NUM.Text);
//---------------------
DirectoryInfo dir = new DirectoryInfo("c:\\pic");
ArrayList JpgList = new ArrayList();
foreach (FileInfo file in dir.GetFiles("*.jpg"))
{
JpgList.Add(file.FullName);
}
int num = JpgList.Count;
//----------------------
if(num!=)//如果文件夹不为空;
{
if (box!=null) //如果有生成的控件,销毁控件;
{
for (int v = ; v < CreatedNum; v++)
{
box[v].Dispose();
box[v].Image = null;
GC.Collect();
}
}
if (N >= num)
N = num;//如果选择显示的数量大于实际图片数量; CreatedNum = N;//实际动态生成的数量;
box = new PictureBox[CreatedNum]; int i = ;
foreach (string v in JpgList)
{
if (i < N)
{
box[i] = new PictureBox();
box[i].Size = new System.Drawing.Size(, );//图片框的大小;
box[i].Location = new System.Drawing.Point(, + i * );//图片排放位置;
box[i].Image = Image.FromFile(v);//图片地址; box[i].SizeMode = PictureBoxSizeMode.Zoom;
//box[i].BorderStyle = BorderStyle.FixedSingle; flowLayoutPanel1.Controls.Add(box[i]); //flowLayoutPanel增加图片
i++;
}
}