What does a ListViewSubtemCollection use for its keys?
Question
I am trying to get the value of some ListViewSubItems, but I have no idea what values it uses for its keys. I have some simple code:
protected override void OnItemDrag(ItemDragEventArgs e)
{
base.OnItemDrag(e);
ListViewItem item = e.Item as ListViewItem;
string val = item.SubItems[???].ToString();
}
The ??? part is where I am having a problem. I cannot figure out what the keys are. I have tried the column names of the ListView with no luck. I would like to use this method instead of using numeric indices.
Solution
The key of the ListViewSubItem
is the Name
property as described here.
Setting the Name equal to the column name, would allow you to index into the SubItems by the name of the column.
And some code as an example
ListViewItem myListViewItem = new ListViewItem();
ListViewItem.ListViewSubItem myListViewSubItem = new ListViewItem.ListViewSubItem();
myListViewSubItem.Text = "This will be displayed";
myListViewSubItem.Name = "my key";
myListViewItem.SubItems.Add(myListViewSubItem);
ListViewItem.ListViewSubItem subItem = myListViewItem.SubItems["my key"];
OTHER TIPS
You can only use the column index to add subitems, but you can make it easier to read by making an enumeration containing the index of each of your columns.
Subitems are only ordered by column index unluckily. So you'd have to access them like:
protected override void OnItemDrag(ItemDragEventArgs e)
{
base.OnItemDrag(e);
ListViewItem item = e.Item as ListViewItem;
string val = item.SubItems[0].ToString();
}