Visual Basic .NET - CheckedListBox Control

The VB.NET CheckedListBox Control is a user interface control that provides a list of items that the user can select by checking or unchecking the box next to each item. It is commonly used to allow users to select multiple items from a list.

Common Properties:

  • Items: Gets or sets the items in the CheckedListBox control.
  • CheckedItems: Gets the collection of checked items in the CheckedListBox control.
  • CheckOnClick: Gets or sets a value indicating whether the check box should be toggled when an item is selected.

Common Methods:

  • SetItemCheckState: Sets the check state of the item at the specified index in the CheckedListBox control.
  • GetItemCheckState: Returns the check state of the item at the specified index in the CheckedListBox control.

Common Events:

  • ItemCheck: Occurs when the checked state of an item is about to change.
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
    ' Cancel the event if the item is the first item.
    If e.Index = 0 Then
        e.NewValue = e.CurrentValue
    End If
End Sub

In this example, the ItemCheck event is handled to prevent the user from checking the first item in the CheckedListBox control. If the user tries to check the first item, the check state is reset to the previous state.

Let's say we have a CheckedListBox control on our form called clbLanguages, and we want to display a list of programming languages and allow the user to select one or more of them. We can use the Items property to add items to the control and the CheckedItems property to get a list of the currently checked items.

Here's the code to add items to the control:

clbLanguages.Items.Add("C#")
clbLanguages.Items.Add("Java")
clbLanguages.Items.Add("Python")
clbLanguages.Items.Add("JavaScript")
clbLanguages.Items.Add("PHP")

And here's the code to get a list of the currently checked items:

Dim checkedItems As New List(Of String)
For Each item As Object In clbLanguages.CheckedItems
    checkedItems.Add(item.ToString())
Next
MessageBox.Show("Selected items: " & String.Join(", ", checkedItems))

This code creates a new List(Of String) to store the checked items, then loops through the CheckedItems property of the control and adds each checked item to the list. Finally, it displays a message box showing the selected items separated by commas.