Results 1 to 3 of 3

Thread: Want an array from ListBox's selected items

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2017
    Location
    UK, France, Belgium, Ireland
    Posts
    34

    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! 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?

  2. #2

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    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:
    1. Dim myArray = myListBox.SelectedItems.
    2.                         Cast(Of Object)().
    3.                         Select(Function(item) myListBox.GetItemValue(item)).
    4.                         Cast(Of Integer)().
    5.                         ToArray()
    Not the shortest one-liner, but a one-liner nonetheless.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width