Search code examples
vb.netwinformscheckedlistbox

Uncheck an item and "Select All" option from CheckedListBox on Windows Form


I have added a checkbox list with some names and a select all option. I am able to select all check boxes in checkbox list when I select (Select all) option.

Problem here is, I am not able to uncheck (Select All) option whenever I uncheck any of the options from check box list.

Below is the vb.net code attached for (Select All) functionality.

Private Sub ChkLB_dl_name_cb_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles ChkLB_dl_name_cb.ItemCheck        
    If e.Index = 0 Then
        Dim newCheckedState As Integer = e.NewValue
        For i As Integer = 1 to ChkLB_dl_name_cb.Items.Count - 1
            Me.ChkLB_dl_name_cb.SetItemCheckState(i, newCheckedState)
        Next
    End If 
End Sub

Below is an image of the checkbox list on the windows form, for your reference.

enter image description here.


Solution

  • In general i would use a Boolean variable to avoid that this handler is called for every item that you change programmatically. This will also fix the problem that you cannot uncheck the first item:

    Private updatingListProgramatically As Boolean = False
    
    Private Sub ChkLB_dl_name_cb_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles ChkLB_dl_name_cb.ItemCheck
        If updatingListProgramatically Then Return
    
        If e.Index = 0 Then
            updatingListProgramatically = True
            For i As Integer = 1 To ChkLB_dl_name_cb.Items.Count - 1
                Me.ChkLB_dl_name_cb.SetItemCheckState(i, e.NewValue)
            Next
        Else
            Dim checked As Boolean = e.NewValue = CheckState.Checked
            If Not checked Then
                updatingListProgramatically = True
                Me.ChkLB_dl_name_cb.SetItemCheckState(0, CheckState.Unchecked)
            End If
        End If
    
        updatingListProgramatically = False
    End Sub
    

    The Else block seems to be what you are asking for.