C#: How to add subitems in ListView

后端 未结 10 1261
眼角桃花
眼角桃花 2020-11-29 07:33

Creating an item(Under the key) is easy,but how to add subitems(Value)?

listView1.Columns.Add(\"Key\");
listView1.Columns.Add(\"Value\");
listView1.Items.Add         


        
10条回答
  •  猫巷女王i
    2020-11-29 07:49

    I think the quickest/neatest way to do this:

    For each class have string[] obj.ToListViewItem() method and then do this:

    foreach(var item in personList)
    {
        listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
    }
    

    Here is an example definition

    public class Person
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public DateTime DOB { get; set; }
        public uint ID { get; set; }
    
        public string[] ToListViewItem()
        {
            return new string[] {
                ID.ToString("000000"),
                Name,
                Address,
                DOB.ToShortDateString()
            };
        }
    }
    

    As an added bonus you can have a static method that returns ColumnHeader[] list for setting up the listview columns with

    listView1.Columns.AddRange(Person.ListViewHeaders());
    

提交回复
热议问题