C#: How to add subitems in ListView

后端 未结 10 1254
眼角桃花
眼角桃花 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条回答
  •  孤独总比滥情好
    2020-11-29 07:52

    I've refined this using an extension method on the ListViewItemsCollection. In my opinion it makes the calling code more concise and also promotes more general reuse.

    internal static class ListViewItemCollectionExtender
    {
        internal static void AddWithTextAndSubItems(
                                       this ListView.ListViewItemCollection col, 
                                       string text, params string[] subItems)
        {
            var item = new ListViewItem(text);
            foreach (var subItem in subItems)
            {
                item.SubItems.Add(subItem);
            }
            col.Add(item);
        }
    }
    

    Calling the AddWithTextAndSubItems looks like this:

    // can have many sub items as it's string array
    myListViewControl.Items.AddWithTextAndSubItems("Text", "Sub Item 1", "Sub Item 2"); 
    

    Hope this helps!

提交回复
热议问题