How to display images in listview C#(jpg, gif, png)

Lionsure 2020-08-10 Original by the website

When displaying many things, if you want to consider efficiency, you usually choose the listview control in Winforms, because other powerful controls have too many things to load, so the efficiency is not so high. The listview can display not only tables, item lists, but also pictures, which is quite versatile.

Only use listview can not complete the image display, but also borrow another control imagelist. It is not unfamiliar for programmers who have set the height and width of listview. Load the image into the imagelist first, and then set its index in the items of imagelist, so that it can be displayed. The following is a specific example of displaying images. The display image types include common image formats such as jpg, gif, png, and bmp.

 

How to display images in listview C#

You need to drag a listview and an imagelist controls to the Form, and then copy the following code to the background and call it in the loading event.

/// <summary>
       /// C# listview image
       /// </summary>
       /// <param name="filePath">The path of images</param>

       private void ShowImages(string filePath)
       {
              lvImg.View = View.LargeIcon;
              lvImg.LargeImageList = imgList;

       DirectoryInfo di = newDirectoryInfo(filePath);
              FileInfo[] afi = di.GetFiles("*.*");

       string temp;
              int j = 0;
              for (int i = 0; i < afi.Length; i++)
              {
                     temp = afi[i].Name.ToLower();
                     if (temp.EndsWith(".jpg"))
                     {
                            AddImg(ref afi[i], ref j, ".jpg");
                     }
                     else if (temp.EndsWith(".jpeg"))
                     {
                            AddImg(ref afi[i], ref j, ".jpeg");
                     }
                     else if (temp.EndsWith(".gif"))
                     {
                            AddImg(ref afi[i], ref j, ".gif");
                     }
                     else if (temp.EndsWith(".png"))
                     {
                            AddImg(ref afi[i], ref j, ".png");
                     }
                     else if (temp.EndsWith(".bmp"))
                     {
                            AddImg(ref afi[i], ref j, ".bmp");
                     }
                     else if (temp.EndsWith(".tiff"))
                     {
                            AddImg(ref afi[i], ref j, ".tiff");
                     }
              }
       }

private void AddImg(ref FileInfo fi, ref int j, string ex)
       {
              imgList.Images.Add(Image.FromFile(fi.FullName));
              lvImg.Items.Add(fi.Name.Replace(ex, ""), j);
              j++;
       }

Call: ShowImages(@"G:\")