I\'m currently working on a listview in winform c# and everytime I click on an empty space on the listview, the selected item is lost.
I know that question asked 10 years ago. But I face the same problem and found a simple and elegant solution just now and sincerely want to share it.
There is a code (in VB.NET but its no big problem to write the same in C#):
Public Class SettingsBox ' Form that contains ListView (lvScreen)
Private nScreenTracer As Integer
Private nSelectedScreen As Integer
Private Sub lvScreen_ItemSelectionChanged(sender As Object,
e As ListViewItemSelectionChangedEventArgs) Handles lvScreen.ItemSelectionChanged
If e.IsSelected Then nScreenTracer = e.Item.Index
End Sub
Private Sub lvScreen_MouseDown(sender As Object,
e As MouseEventArgs) Handles lvScreen.MouseDown
nScreenTracer = -1
End Sub
Private Sub lvScreen_MouseUp(sender As Object,
e As MouseEventArgs) Handles lvScreen.MouseUp
If nScreenTracer = -1 Then
lvScreen.SelectedIndices.Add(nSelectedScreen)
Else
nSelectedScreen = nScreenTracer
End If
End Sub
End Class
This solution works for a single item selection but also can be simply redesigned with List(Of Integer) for multi-select