Want an array from ListBox's selected items
I have a ListBox populated from a view, with ValueMember holding integers.
I have the SelectionMode set to MultiSimple so multiple list items can be selected. I want to put the values of the selected items into an array "SelectedItemsArray"
This is my commonsense way of doing it:
Code:
Dim i As Integer
Dim SelectedItemsArray(ListBox1.SelectedItems.Count) As Integer
For i = 0 To ListBox1.SelectedItems.Count - 1
SelectedItemsArray(i) = ListBox1.SelectedItems(i).Value
Next
However, it fails on "ListBox1.SelectedItems(i).Value" - I get this runtime error:
Code:
System.MissingMemberException occurred
HResult=0x80131512
Message=Public member 'Value' on type 'DataRowView' not found.
So ".Value" isn't valid. The silly thing is I came across the right syntax for retrieving the value of a selected item a few hours ago, but deleted it because I didn't need it at the time. And now I have spent the last hour and a half trying to find it again!:mad: Anyone know what the correct syntax is?
Ideally, I would like to simply pass the whole all the selected items into my array in one go without looping through, but I could not find a way. I wanted to do something like
Code:
SelectedItemsArray = ListBox1.SelectedItems
Is that impossible?
Re: Want an array from ListBox's selected items
Re: Want an array from ListBox's selected items
If you follow that, the one-liner to get an array of selected values would be:
vb.net Code:
Dim myArray = myListBox.SelectedItems.
Cast(Of Object)().
Select(Function(item) myListBox.GetItemValue(item)).
Cast(Of Integer)().
ToArray()
Not the shortest one-liner, but a one-liner nonetheless.