Link to home
Start Free TrialLog in
Avatar of MELeBlanc
MELeBlancFlag for United States of America

asked on

How to restrict a listview with checkboxes to only one selection

I am using VS2005 and have a listview control that is set to display checkboxes and I am only wanting the user to be able to select only one of the checkboxes in the list.  I thought that setting the multiselect property to false would have done this but it only stops the user from highlighting more than one of the items.  Is there a property that I am missing?
Avatar of VBRocks
VBRocks
Flag of United States of America image

You can do it programmatically, using the ItemChecked event of the ListView, for example:

    Private Sub ListView1_ItemChecked(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.ItemCheckedEventArgs) Handles ListView1.ItemChecked

       'Loop through each item in the list and check to see if it is checked and does not have the focus
        For i As Int16 = 0 To Me.ListView1.Items.Count - 1
            If Me.ListView1.Items(i).Checked = True AndAlso _
                Me.ListView1.Items(i).Focused = False Then

                Me.ListView1.Items(i).Checked = False

            End If

        Next
    End Sub

ASKER CERTIFIED SOLUTION
Avatar of Wayne Taylor (webtubbs)
Wayne Taylor (webtubbs)
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
VBRocks - I tried yours but it would only work if the required item was selected prior to checking the box.
You're right...  I created the listview without adding the Text to the items, so it worked for me.  I went
back and added the Text, and then found that to be the case...



However, including the modification to check the Item, it works great:

    Private Sub ListView1_ItemChecked(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.ItemCheckedEventArgs) Handles ListView1.ItemChecked

        'Loop through each item in the list and check to see if it is checked and does not have the focus
        For i As Int16 = 0 To Me.ListView1.Items.Count - 1
            If Me.ListView1.Items(i).Checked = True AndAlso _
                Me.ListView1.Items(i) IsNot e.Item Then

                Me.ListView1.Items(i).Checked = False

            End If

        Next

    End Sub