Andrew
Andrew

Reputation: 1

Getting ListView values into a string array?

I have a ListView control set up in details mode, and on a button press I would like to retrieve all column values from that row in the ListView.

This is my code so far:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Dim items As ListView.SelectedListViewItemCollection = _
    Me.ManageList.SelectedItems
    Dim item As ListViewItem
    Dim values(0 To 4) As String
    Dim i As Integer = 0
    For Each item In items
        values(i) = item.SubItems(1).Text
        i = i + 1
    Next
End Sub

But values just comes out as an empty array. Any ideas? I just want the values array to be filled with the data of that ListView row.

Cheers.

Upvotes: 0

Views: 10393

Answers (4)

Geoff
Geoff

Reputation: 21

Here's the single-line solution:

mylistview.Items.Cast(Of ListViewItem).Select(Function(lvi As ListViewItem)lvi.SubItems(1).Text).ToArray()

Upvotes: 2

Louis van Tonder
Louis van Tonder

Reputation: 3700

Old question, I know... maybe this helps for someones reference.. stumbled upon this question in a search for something else.

This works... not sure if the original poster somehow used an empy colelciton of selected items...

Also, dynamically resizing array based on selected items to overcome unforseen bugs...

    Dim valueArray(mylistview.SelectedItems.Count - 1) As String
    Dim i As Integer

    For Each Item As ListViewItem In mylistview.SelectedItems
        valueArray(i) = Item.Text
        i += 1
    Next

To get subitems, use item.subitems(1).text ... subitems(2).text.. etc

Cheers

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941455

You need to iterate the SubItems, not the selected items. Fix:

If Me.ManageList.Items.Count <> 1 Then Exit Sub
Dim row As ListViewItem = Me.ManageList.Items(0)
Dim values(0 To row.SubItems.Count-1) As String
Dim i As Integer = 0
For Each item As ListViewItem.ListViewSubItem In row.SubItems
  values(i) = item.Text
  i = i + 1
Next

Upvotes: 1

Hans Olsson
Hans Olsson

Reputation: 55009

Just to check, are you aware that item.SubItems(1).Text will get the texts from the second column? And that since you're using SelectedItems it'll only look at the currently selected items in the ListView.

Edit: Also, are you sure there will always just be a maximum of 5 selected items in the ListView? Otherwise you'll have problems with

Dim values(0 To 4) As String

Upvotes: 0

Related Questions