C# – How to add to a specific column in Listview item

.netc++listviewuser-interfacewinforms

I create a listview and the number of columns are determined at runtime. I have been reading texts on the web all over about listview( and I still am) but I wish to know how to add items to a specific column in listview I thought something like:

m_listview.Items.Add("1850").SubItems.Add("yes");

would work assuming the "1850" which is the text of the column would be the target column.

Best Solution

ListViewItems aren't aware of your ListView columns.

In order to directly reference the column, you first need to add all the columns to the ListViewItem.

So... lets say your ListView has three columns A, B and C; This next bit of code will only add data to column A:

ListViewItem item = new ListViewItem();
item.Text = "Column A";

m_listView.Items.Add(item);

To get it to add text to column C as well, we first need to tell it it has a column B...

ListViewItem item = new ListViewItem();
item.Text = "Column A";
item.SubItems.Add("");
item.SubItems.Add("Column C");

m_listView.Items.Add(item);

So now we'll have columns A, B and C in the ListViewItem, and text appearing in the A and C columns, but not the B.

Finally... now that we HAVE told it it has three columns, we can do whatever we like to those specific columns...

ListViewItem item = new ListViewItem();
item.Text = "Column A";
item.SubItems.Add("");
item.SubItems.Add("Column C");

m_listView.Items.Add(item);

m_listView.Items[0].SubItems[2].Text  = "change text of column C";
m_listView.Items[0].SubItems[1].Text  = "change text of column B";
m_listView.Items[0].SubItems[0].Text  = "change text of column A";

hope that helps!