将图像显示在列表视图中

时间:2017-11-17 21:25:53

标签: c# listview listviewitem

我正在用C#编写代码,将指定文件夹中未知数量的图像显示为“listview”我不知道如何获取该特定文件夹中的所有文件。 我知道我必须使用循环和数组,但我不知道如何。 这是我用来访问具有“已知文件名”的文件的代码。 这是一个Windows窗体应用程序。

private void btnZoom_Click(object sender, EventArgs e)
{
    ImageList imgs = new ImageList();
    imgs.ImageSize = new Size(100, 100);

    string[] paths = { };
    paths = Directory.GetFiles("TestFolder");

    try
    {
        foreach (string path in paths)
        {
            imgs.Images.Add(Image.FromFile(path));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    listView1.SmallImageList = imgs;
    listView1.Items.Add("2",0); 
}

2 个答案:

答案 0 :(得分:1)

获取所有可以执行的图像文件

IEnumerable<string> paths = Directory.GetFiles(@"Your Dir", "*.*").Where(x=>x.EndsWith(".png") || x.EndsWith(".jpg")); //add all the extensions you wish in

然后您可以通过列表进行迭代以将其添加到

答案 1 :(得分:0)

以下是工作代码:

enter image description here

,代码是:

   private void button1_Click(object sender, EventArgs e)
    {
        listView1.Items.Clear();
        imageList1.Images.Clear();

        string[] pics = System.IO.Directory.GetFiles( "pics//");
        listView1.View = View.SmallIcon;
        listView1.SmallImageList = imageList1;

        imageList1.ImageSize = new Size(64, 64);
        foreach (string pic in pics)
        {
            imageList1.Images.Add(Image.FromFile(pic));
        }


        for (int j = 0; j < imageList1.Images.Count; j++)
        {

            ListViewItem item = new ListViewItem();

            item.ImageIndex = j;

            listView1.Items.Add(item);


        }

    }

并在设计师处设置:

enter image description here

相关问题