سؤال

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?

هل كانت مفيدة؟

المحلول

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);
    }
}

نصائح أخرى

Try it. It is working code

for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
    if (CheckBoxList1.Items[i].Selected)
    {
         CheckBoxList1.Items.RemoveAt(i);
         i--;
     }
}   

The trick to removing certain elements from a list of those elements is to walk the list in reverse - from count-1 to 0. That way when you remove an element, the indexes of remaining ones you still care about have not changed.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top