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

风流意气都作罢 提交于 2019-12-09 13:09:30

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/17151776/c-sharp-listview-adding-item-with-image-and-text-and-align-the-text-to-left

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!