I need to select and unselect all items in a VB.NET CheckedListBox
control, what is the best way to do this?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With clbCheckedListBox
.Items.Add("Select/UnSelect All")
.Items.Add("Enero")
.Items.Add("Febrero")
.Items.Add("Marzo")
.Items.Add("Abril")
.Items.Add("Mayo")
.Items.Add("Junio")
.Items.Add("Julio")
.Items.Add("Agosto")
.Items.Add("Septiembre")
.Items.Add("Octubre")
.Items.Add("Noviembre")
.Items.Add("Diciembre")
.SelectedIndex = 0
End With
End Sub
Private Sub clbCheckedListBox_ItemCheck(sender As Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
If e.Index = 0 Then
If e.NewValue = CheckState.Checked Then
For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Checked)
Next
ElseIf e.NewValue = CheckState.Unchecked Then
For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Unchecked)
Next
End If
End If
End Sub
After Hours the above code work fine for me !
Do you mean something like this:
Dim checked As Boolean = True ' Set to True or False, as required.
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, checked)
Next
Here I'm just looping through all the CheckedListBox Items and setting their checked state.
Ricardo, perhaps this might be what you are looking for:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim items$() = New String() {"Select/UnSelect All", "Enero",
"Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
"Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"}
For Each Str As String In items : clbCheckedListBox.Items.Add(Str) : Next
End Sub ' Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs)
Private Sub clbCheckedListBox_ItemCheck(sender As System.Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
If e.Index = 0 Then
Dim newCheckedState As CheckState = e.NewValue
For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, newCheckedState)
Next
End If
End Sub
If button.Text = "Select All" Then
For i As Integer = 0 To checklist.Items.Count - 1
checklist.SetItemChecked(i, True)
Next
Button.Text = "Deselect All"
Else
For i As Integer = 0 To checklist.Items.Count - 1
checklist.SetItemChecked(i, False)
Button.Text = "Select All"
Next
End If
I found that clbCheckedListBox.clearSelection()
works well for unselecting all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With