listbox help

02315

New member
Joined
May 17, 2010
Messages
3
Programming Experience
Beginner
Let me give you this scenario,
I have a listbox and a button which has visible turned off
How do I program when there is something on the listbox that has been clicked, button visible will be true and when nothing is clicked the buttons visible will be false?
 
Well, there's a SelectIndexChanged event of the ListBox and you can use the .SelectedIndex property (-1 means nothing's selected) to find out if the button should be visible or not.
 
Double click the ListBox and it'll generate the SelectedIndexChanged event sub, then check for ListBox SelectedIndex greater than -1 and set the button's visible to true, otherwise set it to false.

It doesn't get any easier than that (which is still the same thing, just re-worded, as my previous post)
 
Private Sub lsbDetails_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lsbDetails.SelectedIndexChanged
If lsbDetails.SelectedIndex > -1 Then
btnHeart.Visible = True
Else
btnHeart.Visible = False
End If
End Sub

This doesn't seem to work !
 
By default (when the ListBox's SelectionMode is set to One) the behavior is that when the user clicks below the last item in the ListBox, then the ListBox selects the last item so once something's selected it wont let you have nothing selected via the mouse, but it can be done in code, by setting the SelectedIndex = -1.

Your code works fine, and if you'd like it so the user can click below the last item and the ListBox's SelectedIndex is equal to -1, add this code:
VB.NET:
    Private Sub lsbDetails_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lsbDetails.MouseUp
        lsbDetails.SelectedIndex = lsbDetails.IndexFromPoint(e.Location)
    End Sub
What IndexFromPoint does is it takes the mouse cursor's position (in x, y coords or a point) and returns the index of the item clicked on, if no item was clicked on then it returns -1
 
Back
Top