How to get CheckedListBox selected values in C#
By FoxLearn 12/21/2024 4:06:27 AM 30
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:
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.
- How to update UI from another thread in C#
- How to use Advanced Filter DataGridView in C#
- How to create a Notification Popup in C#
- How to Use Form Load and Button click Event in C#
- How to Link Chart /Graph with Database in C#
- How to Check SQL Server Connection in C#
- How to Generate Serial Key in C#
- How to Search DataGridView by using TextBox in C#