How to get CheckedListBox selected values in C#

By FoxLearn 12/21/2024 4:06:27 AM   30
In Windows Forms (WinForms), the CheckedListBox control provides a powerful way to display a list of items with checkboxes, allowing users to select multiple options simultaneously.

What is a CheckedListBox?

A CheckedListBox is a list control that displays items with checkboxes. Each item in the list can be checked or unchecked, enabling multiple selections.

Imagine you have a form with a CheckedListBox that lists several programming languages, and some of these languages are selected by the user.

Below is a simple UI representation of the CheckedListBox on a form:

checkedlistbox

How to get CheckedListBox selected values in C#?

One of the most common tasks when working with a CheckedListBox is retrieving the items that have been checked by the user. To do this, you can loop through the CheckedItems collection of the CheckedListBox, which contains all the items that have been checked.

The following C# code snippet demonstrates how to retrieve and display the selected items from the CheckedListBox using a foreach loop:

private void btnSubmit_Click(object sender, EventArgs e)
{
    // Using StringBuilder to build the result string
    var selectedLangs = new StringBuilder();

    // Loop through all checked items in the CheckedListBox
    foreach (var lang in clbLanguages.CheckedItems)
    {
        // Append the selected item to the StringBuilder
        if (selectedLangs.Length > 0)
            selectedLangs.Append(", ");
        selectedLangs.Append(lang);
    }

    // Display the selected items in the label
    lblResult.Text = $"You selected: {selectedLangs}";
}

Using the CheckedListBox control in WinForms provides an easy way to handle multiple selections in a user-friendly interface.