Lei Yang
Lei Yang

Reputation: 4335

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

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?

Upvotes: 2

Views: 16063

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460168

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)

Upvotes: 2

max
max

Reputation: 34427

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)

Upvotes: 3

Related Questions