CheckedListBox Control
The CheckedListBox extends the ListBox by allowing each item to have a checkbox. Users can select multiple items by checking them.
What is a CheckedListBox?
A CheckedListBox is like a ListBox where each item has a checkbox next to it. Users can check multiple items, and you can easily see which items are selected.
Common uses: Selecting multiple preferences, choosing toppings, selecting files, multi-select options.
How to Use
- Drag a CheckedListBox onto your form.
- Rename it (e.g.,
clbToppings). - Add items using the Items collection or in code.
- Set CheckOnClick to
trueto check on click.
Code Example
// Add items in code
clbToppings.Items.Add("Pepperoni");
clbToppings.Items.Add("Mushrooms");
clbToppings.Items.Add("Onions");
clbToppings.Items.Add("Extra Cheese");
// Check an item
clbToppings.SetItemChecked(0, true);
// Get all checked items
private void btnShowSelected_Click(object sender, EventArgs e)
{
var selected = new List<string>();
for (int i = 0; i < clbToppings.Items.Count; i++)
{
if (clbToppings.GetItemChecked(i))
{
selected.Add(clbToppings.Items[i].ToString());
}
}
MessageBox.Show($"Selected: {string.Join(", ", selected)}");
}
Exercise
Task: Create a movie night selection tool.
- Add a CheckedListBox with movie genres (Action, Comedy, Drama, Horror, Sci-Fi).
- Add a Button: "Show Selected Genres".
- When clicked, display all selected genres in a message.
- Add a "Select All" button that checks all items.
- Add a "Clear All" button that unchecks all items.
Key Takeaway
Use CheckedListBox when users need to select multiple items from a list.
Use GetItemChecked() to check individual items.