tags:

views:

86

answers:

2

Hello,

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.

+1  A: 

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.

Matthew Iselin
+2  A: 

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
Rex M
+1 for the multiple items mention.
Matthew Iselin
+1 for both answer and comment :)
Madi D.