Question

I am an EXTREME newbie to both C# and more importantly, Visual Studio 2012, so sorry if this seems like an easy question. So I am making a To Do List application as my first little project with VS2012. I have a CheckedListBox named 'checkedListBox1' and a button for deleting the marked (or checked) items all at once named 'markButton'. I have wrote the following code but as you can see in my comment, it does something weird: deletes every other checked item from the collection of checked items I have.


private void markButton_Click(object sender, EventArgs e)
{
    // create a collection of the checked items in the to do list
    // then remove each of them.
    // **** ERROR: It deletes every other checked item 
    // so it deletes indeces 0..2..4..6... each time.
    CheckedListBox.CheckedItemCollection checkedItems = checkedListBox1.CheckedItems;
    for (int i = 0; i < checkedItems.Count; i++)
    {
        checkedListBox1.Items.Remove(checkedItems[i].ToString());
    }
}
Was it helpful?

Solution

When you delete an item, the checkedItems collection gets smaller. Just remove the first one repeatedly:

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

Or remove in reverse order:

for (int i = checkedItems.Count; i > 0; )
{
    checkedListBox1.Items.Remove(checkedItems[--i]);
}

Even better, use CheckedIndices, which avoids the need to search for matching items and confusion in the case of duplicates:

var checkedItemIndices = checkedListBox1.CheckedIndices;
for (int i = checkedItemIndices.Count; i > 0; )
{
    checkedListBox1.Items.RemoveAt(checkedItemIndices[--i]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top