Search code examples
vb.netlistboxitem

Getting Selected Items from a Listbox


Good Wednesday All.

I am running into a brick wall (easy for a shade tree coder to do) I have a Listbox that i populated with a datatable. I want to get the all LicenseID's from the selected items. In other words, if the user selects 3 out of 8 of the list box, I need to get the LicenseID for each of those 3.

Below is how I populated the listbox

 Using cmd As New OleDbCommand(cmdText, conn)
            conn.Open()
            Dim reader As OleDbDataReader = cmd.ExecuteReader()
            dt.Load(reader)
            ListBox1License.DataSource = dt
            ListBox1License.DisplayMember = "InstitutionTypeAbrev"
            ListBox1License.ValueMember = "LicenseID"

        End Using

I need to get the selected items from the listbox to use later.

I am thinking of adding the selected Items to an array.

I have searched around STackOverflow for some examples but none seem to work for me.

Any Help Appreciated


Solution

  • I'll show you how to derive the answer for this yourself:

    I've set up a form:

    enter image description here

    Really simple; the listbox is like your listbox. The button is just there to give me an easy way to stop the code and examine what is going on.

    I wrote some code to populate some things into my listbox. It's a screenshot because it doesn't matter that you have exactly this code, so you don't need to write this code (hence why I'm making it hard to copy paste):

    enter image description here

    I've double clicked my button to make a click handler. I haven't written any code, but I have put a breakpoint on the method declaration - see it's red? Click the margin where the dot is, to put breakpoints in your code. When you hit them, the code stops and waits for you to inspect:

    enter image description here

    I've run my app and clicked my button. The code has stopped and VS has switched to showing me the code, not the app:

    enter image description here

    I can now point to some variable that is in scope (like ListBox1) and see a tooltip, or I can open the Locals/Autos windows and see variables that are in scope and drill into them:

    enter image description here

    Expand you ListBox in the Autos/Locals window. It has a lot of properties. Scroll to SelectedItems:

    enter image description here

    enter image description here

    SelectedItems is a collection of things.. We can tell partly because Microsoft is good at naming collections of things with a plural name, and because the inspector says "enumerate the enumerable" .. it means that it is a bunch of things that we can ForEach to look through

    Expanding it we see that my selecteditems has only one thing selected (i truly did only have one selected item in my list when I clicked the button)

    We can see that an entry in the SelectedItems collection is a DataRowView type of object. We can see that a DataRowView has a Row property that is a DataRow.. This Row is the DataRow in the DataTable to which the list is bound (you set the DataSource to a DataTable; this is a row from that table).

    Every time you dig into the tree another level, that's like using either a dot or an indexer in your code. At this level we've gone listbox1.SelectedItems(0).Row..

    So from this we can see that we need a code like:

    ' we will "enumerate the enumerable"
    For Each drv as DataRowView in listbox1.SelectedItems
    
      Dim originalRow = drv.Row  'we could do this to get the row...
    
      Dim selectedAnimaId = row("AnimalID") ' ..and then index the row to get the animal ID ..
    
      Dim selectedAnimalId = drv("AnimalID") ' ... or it's actually possible to index a DataRowView directly, so you can skip the row part
    
    Next drv
    

    It can be handy to write code while you're stopped on a breakpoint so you can look at the values of things as you're writing, and check you're going in the right direction. You might need to use F10 (or whatever key is associated with "step over"/"step into") to move the yellow bar along and execute code lines one by one:

    enter image description here

    You can only move the code execution along if you've written complete, legal code, but it doesn't have to be logically correct. You can back up and execute again by dragging the yellow arrow in the margin (or right clicking and choosing Set Next Statement). Here I've put some dummy statement in to move along to, so i can check that my animalID is correctly set in X like I expect . I point to X to see the value:

    enter image description here