Check if 2 listboxes have selected item

binga30

New member
Joined
Oct 7, 2014
Messages
3
Programming Experience
1-3
Hi Guys,
Fairly new to VB but enjoying making a small app. One thing I am stuck on is trying to check if 2 listboxes have had an item selected.
If the 2 listboxes have an item selected then enable a button.
I have placed the following code inside the Listbox1 Click Event sub which is public.

VB.NET:
If listbox1.selectedIndex => 0 And listbox2.selectedIndex => 0 Then
    button1.enabled = True
End If

Now this seems to enable my button only if an item is selected in listbox2 and then you need to click twice within listbox1 before it recognises the selection.
I have pieced this together just from google so if I am doing it wrong I would like to know the correct format or the most sound approach.

Thank you
 
Firstly, Click is the wrong event. You should be handling SelectedIndexChanged. It should also be fairly obvious that you need to handle the same event for both ListBoxes. You can duplicate the code in two event handlers, put the code in a single method and then call that from both event handlers of handle both events with a single method.
 
Sorry I did actually have the code inside the SelectedIndexChanged event for Listbox1, didn't have the code on me at the time.

I'm afraid I'm a little more newish and don't quite follow your post.

I have 2 event handlers already (1 for listbox1 and another for listbox2). so you are saying I can do what I want to in a single method?

Is the method where I would have my If statement?

Could you provide a small example please?
 
so you are saying I can do what I want to in a single method?

Is the method where I would have my If statement?

Could you provide a small example please?

There are examples of methods all over the place, including the beginner tutorial I have linked to in my signature below. Write a method (a Sub rather than a Function because it's not returning anything) and put your logic in it, then call that method from both event handlers.
 
Thank you for your patience. I got it working with the following:

Sub canWeStart()
If homeListBox.SelectedIndex >= 0 And awayListBox.SelectedIndex >= 0 Then
startGame.Enabled = True
End If
End Sub

And then called canWeStart in each event handler.
 
Thank you for your patience. I got it working with the following:

Sub canWeStart()
If homeListBox.SelectedIndex >= 0 And awayListBox.SelectedIndex >= 0 Then
startGame.Enabled = True
End If
End Sub

And then called canWeStart in each event handler.

There you go. I was confident that you would be able to do it if you took the time to think it through. Unfortunately a lot of people assume that it will be too hard and don't bother trying. I tend to push a bit harder than most for people to at least have a go because it helps far more in the long run. :)
 
Back
Top