How to refer to a listview subitem by its name,not by its index?

15,330

Solution 1

You can specify name for ListViewSubItem and refer to subitem by that name:

Dim subItem As New ListViewItem.ListViewSubItem
subItem.Name = "c1"
subItem.Text = "SubItem"
Item.SubItems.Add(subItem)

If you add your subitems in this way, MsgBox(ListView1.Items(0).SubItems("c1").Text) will work.

Update:

Unfortunately, this won't work for the first subitem. To fix this, you might need to create all subitems (including default) before ListViewItem:

Dim subItems As ListViewItem.ListViewSubItem() = New ListViewItem.ListViewSubItem(2 - 1) {}
subItems(0) = New ListViewItem.ListViewSubItem()
subItems(0).Name = ListView1.Columns(0).Text
subItems(0).Text = "Default SubItem"
subItems(1) = New ListViewItem.ListViewSubItem()
subItems(1).Name = ListView1.Columns(1).Text
subItems(1).Text = "SubItem 1"
Dim Item As New ListViewItem(subItems, 0)
ListView1.Items.Add(Item)

Solution 2

You could use a little bit of LINQ:

Dim c1Items = From subItem In ListView1.Items(0).SubItems.Cast(Of ListViewItem.ListViewSubItem)()
               Where subItem.Name = "c1"
MsgBox(c1Items.First.Text)

Enumerable.Where filters a sequence of values based on a predicate. First takes the first element. So it takes the first subItem's Text with Name = "c1".

Edit: 'm not so familiar with Winform controls. If the SubItem name is not set, you could use this LINQ query to find the index of the ColumnHeader with the given Text. Then you can use it to get the correct SubItem:

Dim c1ICol = (From col In ListView1.Columns.Cast(Of ColumnHeader)()
              Where col.Text = "c1").First
MsgBox(ListView1.Items(0).SubItems(c1ICol.Index).Text)
Share:
15,330
Lei Yang
Author by

Lei Yang

2017.11 ~ Now: Cerence(formerly Nuance) Shanghai(Chengdu branch) Cloud Service QA Engineer. 2016.4 ~ 2017.10: Intel Security(McAfee), Shenzhen, China, Software Quality Engineer for McAfee Antivirus Software. 2013.3 ~ 2016.3: Motorola Solutions, Chengdu,China, Auto Testing Customer Programming Software for Radios.

Updated on June 04, 2022

Comments

  • Lei Yang
    Lei Yang almost 2 years

    I have been wondering for a while about the code below:

    ListView1.View = View.Details   
    ListView1.Columns.Add("c1")   
    ListView1.Columns.Add("c2")  
    Dim Item As New ListViewItem    
    Item.Text = "1"
    Item.SubItems.Add("2")
    ListView1.Items.Add(Item)
    

    'MsgBox(ListView1.Items(0).SubItems("c1").Text) 'this is wrong  
    MsgBox(ListView1.Items(0).SubItems(0).Text) 'this is right  
    

    I want a way to refer to the column by its name, because it is more readable, and lessens the chance of making a mistake. However, the program won't build. Any thoughts?

  • Tim Schmelter
    Tim Schmelter almost 12 years
    @user1518100: Edited my answer. I'm not so familiar with winform controls, so it may be true that i've overlooked a simple solution or this works not always. But try out yourself.