tags:

views:

134

answers:

4

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.

A: 

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(); 
}
dguaraglia
+1  A: 

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.

Dan Walker
A: 

OK, I can live with that, but why does the class allow a string (key) argument in the first place? Doesn't make sense to me. Oh well, thanks.

Ed Swangren
+1  A: 

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"];

McN