0

我想显示调试目录中的所有图像。也将文件名作为标签。

我唯一的问题是从每个图像的路径中显示文件名。它仅加载 1 个文件名

        int x = 0;
        int y = 0;
        string[] images = Directory.GetFiles(@"images");
        foreach (string image in images)
        {
            PictureBox PB = new PictureBox();
            PB.Image = new Bitmap(image);
            PB.SizeMode = PictureBoxSizeMode.CenterImage;
            PB.Size = new Size(250, 180);
            PB.Location = new Point(x, y);
            panel1.Controls.Add(PB);
            x += 260;
        }
        int a = 0;
        int b = 0;

        string names = System.IO.Path.GetFileName(@"images");
        foreach (string name in names)
        {
            Label label1 = new Label();
            label1.Text = name;
            label1.Location = new Point(a, b);
            this.Controls.Add(label1);
            a += 20;
        }
4

2 回答 2

0
private void Form1_Load(object sender, EventArgs e)
{
    int x = 0;
    int y = 0;
    string[] images = Directory.GetFiles(@"images");
    foreach (string image in images)
    {
        PictureBox PB = new PictureBox();
        PB.Image = new Bitmap(image);
        PB.SizeMode = PictureBoxSizeMode.CenterImage;
        PB.Size = new Size(250, 180);
        PB.Location = new Point(x, y);
        panel1.Controls.Add(PB);
        x += 260;

        Label label1 = new Label();
        label1.Text = Path.GetFileName(name);
        label1.Location = new Point(a, b);
        this.Controls.Add(label1);
        a += 20;
    }

}
于 2013-02-11T01:45:50.570 回答
0

我认为您不需要 2 个循环,您可以只获取文件名并在第一个循环中创建标签,

就像是:

int x = 0;
string[] images = Directory.GetFiles(@"C:\StackOverflow\New Folder");
foreach (string image in images)
{
    Panel item = new Panel();
    item.AutoSize = true;
    item.Location = new Point(x, 0);


    PictureBox PB = new PictureBox();
    PB.Image = new Bitmap(image);
    PB.SizeMode = PictureBoxSizeMode.CenterImage;
    PB.Size = new Size(250, 180);

    Label label1 = new Label();
    label1.Text = System.IO.Path.GetFileName(image);
    label1.Location = new Point(0, 90);
    label1.Width = 250;
    label1.TextAlign = ContentAlignment.MiddleCenter;

    item.Controls.Add(label1);
    item.Controls.Add(PB);

    panel1.Controls.Add(item);
    x += 260;

}

结果在此处输入图像描述

于 2013-02-11T01:51:22.373 回答