Add item to checkedlistbox C#

Tweet0LinkedIn0Facebook0

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:

private void btnAdd_Click[object sender, EventArgs e] { listOptions.Items.Add[txtOption.Text]; }
Code language: C# [cs]

Remove items from the CheckedListBox

To remove checked items, you have to loop in reverse and call RemoveAt[index], like this:

private void btnRemove_Click[object sender, EventArgs e] { for [int i = listOptions.Items.Count - 1; i >= 0; i--] { if [listOptions.GetItemChecked[i]] listOptions.Items.RemoveAt[i]; } }
Code language: C# [cs]

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:

var ints = new List { 1, 2, 3, 4, 5 }; for[int i = 0; i < ints.Count; i++] { ints.RemoveAt[i]; }
Code language: C# [cs]

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:

foreach[var item in listOptions.CheckedItems] { listOptions.Items.Remove[item]; }
Code language: C# [cs]

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.

Tweet0LinkedIn0Facebook0

Video liên quan

Chủ Đề