How to Get Checked Items In a CheckedListBox in C#
By FoxLearn 11/28/2024 2:20:05 PM 7.8K
This article demonstrates how to retrieve both the checked items and their respective indices using C# in a Windows Forms application.
How to Get Checked Items In a CheckedListBox in C#?
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "GetCheckedItems" and then click OK
Design your form as below
A CheckedListBox
is a special type of list box in Windows Forms that displays a list of items, each with a checkbox. Users can select multiple items, and each selected item is marked with a check.
The btnGetItem_Click
method is triggered when the "Get Item" button is clicked. This method clears the listBoxItem
and then loops through the CheckedItems
collection of the CheckedListBox
to add each checked item to listBoxItem
.
private void btnGetItem_Click(object sender, EventArgs e) { //Get items by checkeditems listBoxItem.Items.Clear(); foreach (string s in checkedListBox.CheckedItems) listBoxItem.Items.Add(s); }
The btnGetIndex_Click
method is triggered when the "Get Index" button is clicked. It first clears the listBoxIndex
and then loops through the CheckedIndices
collection, which contains the indices of the checked items in the CheckedListBox
.
private void btnGetIndex_Click(object sender, EventArgs e) { //Get items by index listBoxIndex.Items.Clear(); for (int i = 0; i < checkedListBox.CheckedIndices.Count; i++) listBoxIndex.Items.Add(checkedListBox.CheckedIndices[i]); }
Add code to handle your winform as below
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GetCheckedItems { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
When you need to display the checked items to the user, for instance, in another list or output window, the CheckedItems
collection is the easiest way to fetch those items.
Sometimes you may need to keep track of which items the user has checked in terms of their indexes. The CheckedIndices
collection allows you to fetch the indices of the checked items easily.
By using the CheckedItems
and CheckedIndices
properties of the CheckedListBox
, you can quickly retrieve both the items that are checked and their respective indices.
VIDEO TUTORIAL
- How to make a File Explorer in C#
- How to Print Text in a Windows Form Application Using C#
- How to fill ComboBox and DataGridView automatically in C#
- How to Read text file and Sort list in C#
- How to pass ListView row data into another Form in C#
- How to read and write to text file in C#
- How to make a Countdown Timer in C#
- How to Display selected Row from DataGridView to TextBox in C#