I am trying to remove all listbox items that contain all spaces(11).I am stuck. This code doesnt remove the items

for (int i = 0; i < tree.Items.Count; i++)
            {
                if (tree.Items[i].ToString().Contains("     "))
                {
                    tree.Items.RemoveAt(i);
                }
            }

Recommended Answers

All 3 Replies

You are changing the list as you iterate through it.
This always causes problems.
Try reversing the search order.

for (int i = tree.Items.Count - 1; i > 0; i--) 
{
    if (tree.Items[i].ToString().Contains("     "))
    {
        tree.Items.RemoveAt(i);
    }
}

Note: If the list is DataBound then you must modify the DataSource.

Instead of using that, I used a string. What way do you think is better, more effeciant? Also thanks for the help.

EDIT: I'm gonna use your method, I saw a time difference, Thanks

Nick is correct, if you are removing item you should start at the end and work forwards. Imagine your index is zero, the item at index zero is all spaces so you remove it. The items in the collection will then move down into the space so item one becomes item zero...but you have already tested zero so you increment your index and test item at index one. If the item that was originally at index one was all spaces it wont be removed. Every time you remove an item you skip one. By starting at the last item and moving to the first you avoid that problem.
This is the reason you get an exception if you alter a collection inside a foreach loop :)

Just a note, you are checking for:

Contains("     "))

what happens if the item contains

"  "

or

"                "

?
You can use trim to clear of the excess white space then check for empty strings:

string spaces = "           ";
    if (spaces.Trim() == string.Empty)
    {
        //do stuff
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.