prevent listview to lose selected item

后端 未结 6 1866
失恋的感觉
失恋的感觉 2021-01-18 03:43

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.

6条回答
  •  梦谈多话
    2021-01-18 04:13

    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

提交回复
热议问题