how can i check if an item is selected or not in a listbox?

ethicalhacker

Well-known member
Joined
Apr 22, 2007
Messages
142
Location
Delhi,India
Programming Experience
5-10
Im using
VB.NET:
Dim a As String = ListBox1.SelectedItem
to get the selected item on click of a button. I want to make sure that there is no error if the user clicks on the button without selecting an item, he should get a message "first select an item". Is there any kind of try catch exception I can use?
 
Check first that the item IsNot Nothing.
 
Verify that item in listbox is selected

Very simple:

If ListBox1.SelectedIndex > 0 Then
' do something with item at selected index
Else
MessageBox.Show("Please select an item from the list and try again.")
End If
 
In order to implement my suggestion set the Enabled property of the Button False in the designer. Handle the SelectedIndexChanged event of the ListBox and do this:
VB.NET:
myButton.Enabled = (myListBox.SelectedIndex <> -1)
 
Back
Top