Click to deselect single-select listbox
I want to make a single-select listbox deselect the selected item when you click on it (like a simple multiselect, except that only one item can ever be selected). Is there a simple way to do this? Or would it be easier to come at it the other way and make a simple multiselect listbox that deselects an old item when you select a new one?
Re: Click to deselect single-select listbox
like this?...
Code:
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
' NOTE: ListBox1.SelectionMode = SelectionMode.One
Static lastIndex As Integer = -1
If ListBox1.SelectedIndex > -1 Then
If lastIndex > -1 Then
If lastIndex = ListBox1.SelectedIndex Then
ListBox1.SelectedIndex = -1
End If
End If
End If
lastIndex = ListBox1.SelectedIndex
End Sub
Edit, or simply?...
Code:
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Static lastIndex As Integer = -1
If lastIndex = ListBox1.SelectedIndex Then
ListBox1.SelectedIndex = -1
End If
lastIndex = ListBox1.SelectedIndex
End Sub
Re: Click to deselect single-select listbox
try this. it's not perfect, but close to what you want:
Code:
Public Class Form1
Private canSelect As Boolean = True
Private Sub ListBox1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseClick
If ListBox1.IndexFromPoint(e.Location) = -1 Then Return
If Not canSelect Then
ListBox1.SelectedItem = Nothing
End If
canSelect = Not canSelect
End Sub
End Class
Re: Click to deselect single-select listbox
That first one works perfectly, although I'm not exactly sure how.