How to populate a ListView by objects from a special class

时间:2015-09-01 22:13:24

标签: c# winforms

I'm new to C# and I'm trying to design a ListView and populate it by objects from a special class, let's say Class1 and show the Class1.title as the text for each object. How can I do that? It looks like there is no DataSource property in the ListView in C#.

1 个答案:

答案 0 :(得分:0)

You can use the Tag property of ListViewItem to store your original object

public partial class Form1 : Form
{
    private class Foo
    {
        public string Title { get; set; }
        public int DontShowMe { get; set; }
    }
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Foo foo = new Foo() { Title = "Hello", DontShowMe = 42 };
        ListViewItem item = new ListViewItem() { Text = foo.Title, Tag = foo };
        listView1.Items.Add(item);
    }
}

If you later look at a particular entry in the ListView, you can cast Tag (which is type object) back to your actual type.