Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listbox Selected Item Checking

Tags:

.net

vb.net

My code follows. I have six items (indices 0-6) and I'm trying to check if one has been selected or not. If not, then messagebox yells at you to select one. If it does, it tells you what you have selected. I'm having a horrible brain fart and contemplated coming here for about 45 minutes as I couldn't get it.

If ListBox1.SelectedItem.ToString <> "" Then
    MessageBox.Show("You selected " + ListBox1.SelectedItem.ToString)
Else
    MessageBox.Show("Please select an item.")
End If

Thanks for relieving me of stupidty.


2 Answers

If this is a System.Windows.Forms ListBox, it can have multiple items:

If ListBox1.SelectedItems.Count == 0

If this is a System.Web.UI.WebControls ListBox, it can also have multiple items but the properties don't reflect that. If one or more items is selected, the first item will be the SelectedIndex, otherwise it is -1:

If ListBox1.SelectedIndex > -1
like image 88
Rex M Avatar answered Apr 22 '26 01:04

Rex M


Try checking the listbox's SelectedIndex property instead.

Kind of like:

If listBox.SelectedIndex = -1 Then
    ' Nothing selected!
Else
    ' Something selected
End If

This is of course assuming you have your ListBox setup to only allow single selection.

like image 27
Matthew Iselin Avatar answered Apr 22 '26 01:04

Matthew Iselin