Search code examples
c#listviewlistviewitem

Showing images into a list view


I am writing a code in C# to show the unknown number of images from a specified folder into a "listview" I don't know how to get all the files present in that specific folder. I know I have to use a loop and array but I don't know how. Here is the code which I use to access files with the "known name of file". It's a windows form app.

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); 
}

Solution

  • Here is the working code:

    enter image description here

    and the code is :

       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);
    
    
            }
    
        }
    

    and at designer set this:

    enter image description here