user6327483
user6327483

Reputation:

Forms - Add a picture to every item in a ListView

How do I add pictures to a ListView in C# Forms?
My program gets all subfolders of a directory and is able to display the names in a ListView.
But I am having trouble adding a folder icon to each listview Item.
This is the code I have tried so far:

string storedir = 
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + 
"\\myfolder";

ImageList imgl = new ImageList();
//Get the folder icon from resources
imgl.Images.Add(Properties.Resources.folder);

DirectoryInfo dir = new DirectoryInfo(storedir);
foreach (DirectoryInfo getdirs in dir.GetDirectories("*.*")) {
    ListViewItem lItem = listView1.Items.Add(getdirs.Name, imgl.Images.Count - 1);
}


No success tho:

Screenshot

Can anyone help me?

EDIT:

It works now. Thanks to @Gusman and @LarsTech ! I added an ImageList Control to the form and named it "imgl". Then I set it as Small- and LargeImageList on the ListView control and finally I removed

ImageList imgl = new ImageList();

Thank you!

Upvotes: 0

Views: 844

Answers (1)

Nino
Nino

Reputation: 7095

As Lars said in comment, you have to set LargeImageList property to a reference of imagelist

so, assign image list like this:

listView1.LargeImageList = imgl;

next, you have to add 0-based index of your image. In your imagelist 0 means first image, 1 second etc. Something like this (no need to access last image in list by specifying last index):

foreach (DirectoryInfo getdirs in dir.GetDirectories("*.*")) {
    ListViewItem lItem = listView1.Items.Add(getdirs.Name, 0);

Upvotes: 1

Related Questions