Add images in ListView (C#)

We'll develop an application in which we'll get all images from a directory and add those images in a ListView.
  • Open visual studio and create new "Windows Form Application" project.
  • Go to Toolbox and drag and drop a ListView.
  • Change name of that ListView to "imageListView".
  • Double at form and it'll navigate you to its load event.
  • Now add following code in form load event.
private void Form1_Load(object sender, EventArgs e)
{
    ImageList imageList = new ImageList();

    // Clear imageList and imageListView
    this.imageListView.Items.Clear();
           
    // Get directory info
    DirectoryInfo dir = new DirectoryInfo(@"D:\Images");

    // Read all files in directory
    foreach (FileInfo file in dir.GetFiles())
    {
        try
        {
            imageList.Images.Add(Image.FromFile(file.FullName));
        }
        catch
        {
            Console.WriteLine("This is not an image file");
        }
    }

    imageList.ImageSize = new Size(32, 32);

    this.imageListView.View = View.LargeIcon;

    for (int counter = 0; counter < imageList.Images.Count; counter++)
    {
        ListViewItem item = new ListViewItem();
        item.ImageIndex = counter;
        this.imageListView.Items.Add(item);
    }

    this.imageListView.LargeImageList = imageList;
}
Now run the application (F5) and test it.
Other related and helpful articles.

Comments

Popular posts from this blog

Add button & its click event programmatically in C#

Resize and Save Multiple Images in C#