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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With