Checkedlistbox c как проверить выбранные элементы
Элемент CheckedListBox представляет симбиоз компонентов ListBox и CheckBox. Для каждого элемента такого списка определено специальное поле CheckBox, которое можно отметить.
Все элементы задаются в CheckedListBox задаются в свойстве Items . Также, как и для элементов ListBox и ComboBox, мы можем задать набор элементов. По умолчанию для каждого добавляемого нового элемента флажок не отмечен:
Чтобы поставить отметку в checkBox рядом с элементом в списке, нам надо сначала выделить элемент и дополнительным щелчком уже установить флажок. Однако это не всегда удобно, и с помощью свойства CheckOnClick и установке для него значения true мы можем определить сразу выбор элемента и установку для него флажка в один клик.
Другое свойство MultiColumn при значении true позволяет сделать многоколоночный список, если элементы не помещаются по длине:

Выделенный элемент мы также можем получить с помощью свойства SelectedItem , а его индекс — с помощью свойства SelectedIndex . Но это верно только, если для свойства SelectionMode установлено значение One , что подразумевает выделение только одного элемента.
При установке для свойства SelectionMode значений MultiSmple и MultiExtended можно выбрать сразу несколько элементов, и тогда все выбранные элементы будут доступны в свойстве SelectedItems , а их индексы — в свойстве SelectedIndeces .
И поскольку мы можем поставить отметку не для всех выбранных элементов, то чтобы отдельно получить отмеченные элементы, у CheckedListBox имеются свойства CheckedItems и CheckedIndices .
Для добавления и удаления элементов в CheckedListBox определены все те же методы, что и в LstBox:
Add(item) : добавляет один элемент
AddRange(array) : добавляет в список массив элементов
Insert(index, item) : добавляет элемент по определенному индексу
Remove(item) : удаляет элемент
RemoveAt(index) : удаляет элемент по определенному индексу
Clear() : полностью очищает список
SetItemChecked и SetItemCheckState
К особенностям элемента можно отнести методы SetItemChecked и SetItemCheckState . Метод SetItemChecked позволяет установить или сбросить отметку на одном из элементов. А метод SetItemCheckState позволяет установить флажок в одно из трех состояний: Checked (отмечено), Unchecked (неотмечено) и Indeterminate (промежуточное состояние):
C# Checked ListBox Control
The CheckedListBox control gives you all the capability of a list box and also allows you to display a check mark next to the items in the list box.

The user can place a check mark by one or more items and the checked items can be navigated with the CheckedListBox.CheckedItemCollection and CheckedListBox.CheckedIndexCollection .
Checkedlistbox add items
Syntax
You can add individual items to the list with the Add method . The CheckedListBox object supports three states through the CheckState enumeration: Checked, Indeterminate, and Unchecked.

If you want to add objects to the list at run time, assign an array of object references with the AddRange method . The list then displays the default string value for each object.

By default checkedlistbox items are unchecked .
Check all items in a Checkedlistbox
If you want to check an item in a Checkedlistbox, you need to call SetItemChecked with the relevant item.
Parameters
- index(Int32) — The index of the item to set the check state for.
- value(Boolean) — true to set the item as checked; otherwise, false.
If you want to set all items in a CheckedListBox to checked, change the value of SetItemChecked method to true.
Uncheck all items in a Checkedlistbox
If you want to set all items in a CheckedListBox to unchecked, change the value of SetItemChecked method to false.

CheckedListBox DataSource
Following example shows how to bind a DataSource to CheckedListBox
How to programmatically check an item in a CheckedListBox in C#?
I have a CheckedListBox, and I want to automatically tick one of the items in it.
The CheckedItems collection doesn’t allow you to add things to it.
![]()
6 Answers 6
You need to call SetItemChecked with the relevant item.
The documentation for CheckedListBox.ObjectCollection has an example which checks every other item in a collection.
![]()
This is how you can select/tick or deselect/untick all of the items at once:
![]()
In my program I’ve used the following trick:
How does things works:
SetItemChecked(int index, bool value) is method which sets the exact checked state at the specific item. You have to specify index of item You want to check (use IndexOf method, as an argument specify text of item) and checked state (true means item is checked, false unchecked).
This method runs through all items in CheckedListBox and checks (or unchecks) the one with specified index.
For example, a short piece of my code — FOREACH cycle runs through specified program names, and if the program is contained in CheckedLitBox (CLB. ), checks it:
WinForms – How to programmatically check items in CheckedListBox
A CheckedListBox allows the user to check one or more checkboxes. Sometimes you’ll want to be able to check the boxes programmatically. For example, you may want to allow the user to check or uncheck all boxes at once. Or perhaps you want to persist the values the user checked and load them later.
To programmatically check a box, you can use either of the following methods:
In this article, I’ll show examples of how to check / uncheck all boxes at once, and how to load previously selected values. I’ll use the following WinForm:

Initialize the CheckedListBox
First, add an enum with the [Flags] attribute. This simplifies things if your goal is to persist the selected values and load them later.
Next, initialize the CheckedListBox in the form constructor, like this:
Checking or unchecking all checkboxes
To check or uncheck all checkboxes at once, you loop through the checkboxes and call SetItemCheckState(), like this:
Loading previously checked values
Let’s say you persisted the checked values to the database, and you want to load the checked values when the user clicks a button.
To do that, you can loop through the enum values and set the checked state based on the result of HasFlag(), like this:
Clicking the load button will check the CSharp, Java, and Python checkboxes and leave all the other checkboxes unchecked.