Wednesday, June 2, 2010

How to delete all checked items in CheckedListBox

Remove all checked items from a CheckedListBox
for (int i = checkListDays.Items.Count - 1; i >= 0; i--)
{
if (checkListDays.GetItemChecked(i))
checkListDays.Items.RemoveAt(i);
}



Another solution is to save all the items in a List by iterating through CheckedListBox.CheckedItems, and then iterating through the resulting List and CheckedListBox.Items.Remove(object from List<>).


These solutions differ slightly in efficiency. The first solution iterates through the CheckedListBox only once, thanks to on-the-fly item removal, thus O(n). The second solution could iterate through the CheckedItems list, which could contain all items, and then iterate through the List<>, thus O(2n). But, O(2n) == O(n), because the 2 is dropped, thus the difference in efficiency is insignificant. I do like the first solution more however, because of its elegance.


References
1.
Delete all checked items in CheckedListBox | debugging:

No comments:

Post a Comment

There was an error in this gadget