Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a foreach loop to delete all of the control in a panel?

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?

like image 849
Sergio Tapia Avatar asked Nov 26 '22 22:11

Sergio Tapia


2 Answers

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();
like image 123
Reed Copsey Avatar answered Nov 29 '22 11:11

Reed Copsey


Does this work for you?

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

Edited to emphasize the CKret comment.

like image 39
Austin Salonen Avatar answered Nov 29 '22 11:11

Austin Salonen