How to loop through checkedlistbox and remove selected items in c#

Bryuk picture Bryuk · May 4, 2013 · Viewed 8.6k times · Source

In my app users can add some item in checkedlistbox, then user selects some element and clicks the button "Remove". How can I loop through my checkedListBox and remove selected items?

Answer

Damith picture Damith · May 4, 2013

You can check the count of checked items and remove on while loop as below

while (checkedListBox1.CheckedItems.Count > 0) {
   checkedListBox1.Items.Remove(checkedListBox1.CheckedItems[0]);
}

OR

int lastIndex =checkedListBox1.Items.Count-1;
for(int i=lastIndex ; i>=0 ; i--)
{
    if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
    {
             checkedListBox1.Items.RemoveAt(i);
    }
}