Normally the items in a CheckedListBox are hardcoded or added programmatically [from an enum, or from some data source]. But sometimes you may want to allow the user to add and remove items from a CheckedListItem.
In this article Ill show how to add items and remove them. Ill be working with text, and will be using the following form:
Add items to the CheckedListBox
You add items by calling list.Items.Add[] like this:
Remove items from the CheckedListBox
To remove checked items, you have to loop in reverse and call RemoveAt[index], like this:
Cant loop forward and remove items
You cant loop forward and remove items from a list. When you remove an item, it changes the index of the items following that removed item. This leads to incorrect results.
As an example of why you cant loop forward to remove items, consider the following incorrect code:
You may think this would remove all items in the list, but it skips over items due to the index of those items changing. At the end, the list still has { 2, 4 }.
When you loop in reverse and remove items, it changes the index of the items that you already looped over, so theres no side effects.
Cant use a foreach
You may be thinking, why not use a foreach on list.CheckedItems to remove items? Like this:
But you cant modify a list youre enumerating. Youll get this exception:
System.InvalidOperationException: List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.