Question

Here's the code I have:

private void ClearSearchResults()
    {
        foreach (Control X in panel1.Controls)
        {
            panel1.Controls.Remove(X);
        }
    }

The problem is, when I run this method, only a single item is deleted, then if I click on a button again so the method can run again, another is deleted.

If I have 10 control in my panel, I'd have to click the "Delete" button on my program many times for all the control to be deleted.

What can I do in this case?

Was it helpful?

Solution

Does this work for you?

private void ClearSearchResults()
{
    panel1.Controls.Clear();
}

Edited to emphasize the CKret comment.

OTHER TIPS

You, in general, can't remove from a collection while iterating an enumerable generated from it. Instead of using foreach, the typical approach is to use a for loop working backwards:

private void ClearSearchResults()
{
    for(int i=panel1.Controls.Count-1;i>=0;--i) {
        panel1.Controls.RemoveAt(i);        
        // or
        // Control X = panel1.Controls[i];
        // panel1.Controls.Remove(X);
    }
}

However, in this case, just use clear:

panel1.Controls.Clear();

I believe you are changing the IEnumareble when you remove an item from it while iterating it.

Try to use a simple for loop instead of a foreach.

For a start you shouldn't edit the IEnumerable collection within a foreach loop. You should be using a for loop or a while.

I.e.

private void ClearSearchResults()
    {
        while (panel1.Controls.Count > 0)
        {
            panel1.Controls.RemoveAt(0);
        }
    }

or just use:

 panel1.Controls.Clear();

Maybe this:

panel1.Controls.Clear()

As I don't know the kind of panel you use, you can generally call panel1.Controls.Clear

  private void ClearSearchResults()
        {
            foreach (Control X in panel1.Controls)
            {
                panel1.Controls.Remove(X);
            }
            if (panel1.Controls.Count > 0)
            { 
                ClearSearchResults();
            }
        }
            int n;
            n = panel1.Controls.Count-1;

            for (int i = 0; i <= n; i++ )
            {
                Control c = panel1.Controls[0];
                panel1.Controls.Remove(c);
            }

Actually you can't use Remove because it breaks the iterator so simple solution would be something like this :

var controls = in c from panel1.Controls select c;
foreach(Controls _control in controls)
{
   panel1.Controls.Remove(_control);
}

but of course you don't want to stick to Loop then go ahead and use panel1.Controls.Clear()

while (panel1.Controls.Count != 0)
{
    foreach (Control c in panel1.Controls)
    {
        panel1.Controls.Remove(c);
    }
}

Another way !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top