C# Listview adding item with image and text, and align the text to left

Stefan R picture Stefan R · Jun 17, 2013 · Viewed 41.6k times · Source

I'm trying to create some test programs, just for fun to learn c#, and I came to something I really couldn't figure out.

I wanted to add an image to an item in a listview. I found an article on Stackoverflow explaining how to do this, and it worked. However, I cannot add extra text to the item. I'd like to have an image with text next to it. My current code:

ImageList Imagelist = new ImageList();
private void Form1_Load(object sender, EventArgs e)
    {
        //retrieve all image files
        String[] ImageFiles = Directory.GetFiles(@"C:\test");
        foreach (var file in ImageFiles)
        {
            //Add images to Imagelist
            Imagelist.Images.Add(Image.FromFile(file));
        }
        //set the amall and large ImageList properties of listview
        listView1.LargeImageList = Imagelist;
        listView1.SmallImageList = Imagelist;

        listView1.Items.Add(new ListViewItem() { ImageIndex = 0});
    }

Obviously it will only add one image, it's meant to. Anyway, how would I enter text next to the image? For example

listView1.Items.Add(new ListViewItem() { ImageIndex = 0} "Image 1");

The text must be located behind the image.

I've also got a second question. I do not have columns (adding them doesn't do the trick either). I would like to have the item aligned to the left side of the ListView. How could I do this?

Thank you!

Answer

Andre picture Andre · Jun 17, 2013

This should solve your problems.

listView1.View = View.Details; // Enables Details view so you can see columns
listView1.Items.Add(new ListViewItem { ImageIndex = 0, Text = "Image 1" }); // Using object initializer to add the text