Search code examples
vb.netlistviewselecteditemlistviewitem

Are ListviewItems ever truely deselected?


I have a listview with several items in it. If I have an item selected and click in an empty white space or anywhere else on the form the highlight is removed but .FocusedItem & .SelectedItems still report an item is selected.

I have events that I want to trigger when no listviewitems are selected, but that never seems to occur. How do I detect if no items are selected or does that ever actually happen after that first item gets clicked?

Private Sub lstCats_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCats.SelectedIndexChanged
    If IsNothing(lstCats.FocusedItem) Then
        DisableGUI()
    Else
        EnableGUI()
        DisplayQuestions()
    End If
End Sub

Basically DisableGUI() will never execute. Thanks!


Solution

  • You can deselect all items in the ListView by clicking on an empty part of the ListView control (that is not on one of the items). For example:

    Private Sub lstCats_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCats.SelectedIndexChanged
        If lstCats.SelectedItems.Count = 0 Then
            DisableGUI()
        Else
            EnableGUI()
            DisplayQuestions()
        End If
    End Sub
    

    Note if you click on an item in the ListView, SelectedItems will be > 0. If you click on the background of the ListView (not on an item), SelectedItems will be = 0. This assumes that there is part of the ListView control that does not contain an item.