adding image to listView

nirmus picture nirmus · Aug 5, 2011 · Viewed 11k times · Source

I have this problem. I want to add image to listView. Exactly I want use openFileDialog for choose image on disc, load file to aplication and show them in listView.

Now I do it like this:

        openFileDialog1.Filter = "png (*.png)|*.png";
        openFileDialog1.Multiselect = true;

        if ( openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {    
            string[] files = openFileDialog1.FileNames;

            foreach ( var pngFile in files ) {
                try {
                    Bitmap image = new Bitmap( pngFile );
                    imageList1.Images.Add( image );
                } catch {
                }
            }
            listView1.LargeImageList = imageList1;
            listView1.Refresh();
        }

But it doesn't work. What do I make wrong?

edit

I get blank listView. Nothing error.

Answer

Hans Passant picture Hans Passant · Aug 5, 2011

Well, that's fine. But you only added an image to the image list. You haven't modified an item in the list view that actually uses that added image. Add this line of code and tweak as necessary:

  listView1.Items.Add(new ListViewItem("Added an image", imageList1.Images.Count - 1));

Also ensure that listView1.LargeImages = imageList1. You set that in the designer.