开发者

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 com开发者_Python百科es out as an empty array. Any ideas? I just want the values array to be filled with the data of that ListView row.

Cheers.


Here's the single-line solution:

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


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜