C#: How to add subitems in ListView


Question

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("sdasdasdasd");
//How to add "asdasdasd" under value?
1
25
8/28/2015 10:04:16 PM

Accepted Answer

Like this:

ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add("SubItem");
listView1.Items.Add(lvi);
24
4/8/2009 8:49:04 AM

You whack the subitems into an array and add the array as a list item.

The order in which you add values to the array dictates the column they appear under so think of your sub item headings as [0],[1],[2] etc.

Here's a code sample:

//In this example an array of three items is added to a three column listview
string[] saLvwItem = new string[3];

foreach (string wholeitem in listofitems)
{
     saLvwItem[0] = "Status Message";
     saLvwItem[1] = wholeitem;
     saLvwItem[2] = DateTime.Now.ToString("dddd dd/MM/yyyy - HH:mm:ss");

     ListViewItem lvi = new ListViewItem(saLvwItem);

     lvwMyListView.Items.Add(lvi);
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon