How do you get value of a selected item in a listview?

bonedoc
06-11-2006, 01:54 PM
I was usning a listbox, and then started using a listview. I could get the value of the item I was selecting in the listbox with:

Dim x as string
x=listbox1.selecteditem

But, a listview does not have "selectedItem", so I cannot fing a way to get the value from the item selected. There is a "SelectedItems" for the listview, but I get the error

Dim x as string
x=listview1.selecteditems

"Collection cannot be converted to string"

How can I get the value of an item in a listview with a click or index changed event?

Allen G
06-13-2006, 01:24 AM
I was usning a listbox, and then started using a listview. I could get the value of the item I was selecting in the listbox with:

Dim x as string
x=listbox1.selecteditem

But, a listview does not have "selectedItem", so I cannot fing a way to get the value from the item selected. There is a "SelectedItems" for the listview, but I get the error

Dim x as string
x=listview1.selecteditems

"Collection cannot be converted to string"

How can I get the value of an item in a listview with a click or index changed event?


Public ReadOnly Property SelectedItems() As System.Windows.Forms.ListView.SelectedListViewItemCollection
Member of: System.Windows.Forms.ListView
Summary:
Gets the items that are selected in the control.

Return Values:
A System.Windows.Forms.ListView.SelectedListViewItemCollection that contains the items that are selected in the control. If no items are currently selected, an empty System.Windows.Forms.ListView.SelectedListViewItemCollection is returned.


The error you recieved is valid, SelectedItems is a Collection and therefore you can't convert it to a String directly. Now there are 2 ways of getting the selected value(s).

First, do you want only the first selected value?

Private Sub lvPlaylist_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvPlaylist.SelectedIndexChanged

If Not lvPlaylist.SelectedItems.Count = 0 Then
Debug.WriteLine(lvPlaylist.SelectedItems.Item(0).Text, "Selected")
End If

End Sub


Or you could do it this way, if multiple items are selected.

Private Sub lvPlaylist_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvPlaylist.SelectedIndexChanged

If Not lvPlaylist.SelectedItems.Count = 0 Then
For Each item As ListViewItem In lvPlaylist.SelectedItems
Debug.WriteLine(item.Text, "Selected")
Next
End If

End Sub

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum