Results 1 to 4 of 4

Thread: Click to deselect single-select listbox

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Oct 2011
    Posts
    152

    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?

  2. #2
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    4,255

    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
    Last edited by Edgemeal; May 22nd, 2013 at 03:20 PM.

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,415

    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

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Oct 2011
    Posts
    152

    Re: Click to deselect single-select listbox

    That first one works perfectly, although I'm not exactly sure how.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width