Listbox.selected index change variable assignment

Wannabe picture Wannabe · Apr 3, 2011 · Viewed 12.1k times · Source

Hi there What is the correct way of assigning the selected index's value from a listbox to a variable? The user selects an item in a listbox and then the output changes depending on their selection.

I use:

variablename = listbox.text

in the listBox_SelectedIndexChanged event and this works.

When I use the button_click event I use:

variablename = listbox.selectedindex 

But this does not work in the listbox_selectedindexchanged event.

Please could you let me know if it is okay to use it like I did above or if I will run into problems and why you cannot use the selectedindex method.

Thanks!

Answer

XIVSolutions picture XIVSolutions · Apr 3, 2011

A. It sounds like your variable is a string, and yet you are trying to assign to it the value returned by the SelectedIndex Property, which is an integer.

B. If you are trying to retrieve the value of the item associated with the SelectedINdex of the Listbox, use the Index to return the Object itself (the listbox is a list of Objects, which are often, but not always, going to be strings).

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    'THIS retrieves the Object referenced by the SelectedIndex Property (Note that you can populate
    'the list with types other than String, so it is not a guarantee that you will get a string
    'return when using someone else's code!):
    SelectedName = ListBox1.Items(ListBox1.SelectedIndex).ToString
    MsgBox(SelectedName)
End Sub

THIS is a little more direct, using the SelectedItem Property:

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

    'This returns the SelectedItem more directly, by using the SelectedItem Property
    'in the event handler for SelectedIndexChanged:
    SelectedName = ListBox1.SelectedItem.ToString
    MsgBox(SelectedName)

End Sub