Intermediate 10 min read Control #3

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

  1. Drag a CheckedListBox onto your form.
  2. Rename it (e.g., clbToppings).
  3. Add items using the Items collection or in code.
  4. Set CheckOnClick to true to 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.

  1. Add a CheckedListBox with movie genres (Action, Comedy, Drama, Horror, Sci-Fi).
  2. Add a Button: "Show Selected Genres".
  3. When clicked, display all selected genres in a message.
  4. Add a "Select All" button that checks all items.
  5. 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.