How can I use a foreach loop to remove an entire control in a panel?

Here is the code I have:

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

The problem is that when I run this method, only one element is deleted, and then when I press the button again so that the method can be started again, the other is deleted.

If I have 10 controls in my panel, I will have to repeatedly click the "Delete" button in my program for all the controls that need to be removed.

What can I do in this case?

+4
source share
10 answers

Does this work for you?

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

Edited to emphasize CKret's comment.

+14
source

You, in general, cannot remove from the collection, iterations of the enumerable from it. Instead of using foreach, a typical approach is to use a for loop that works in the opposite direction:

 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(); 
+16
source

I believe that you are changing IEnumareble when you remove an element from it during iteration.

Try using a simple for loop instead of foreach.

+8
source

For starters, you should not edit the IEnumerable collection in a foreach loop. You should use a for or while loop.

those.

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

or just use:

  panel1.Controls.Clear(); 
+3
source

Perhaps it:

 panel1.Controls.Clear() 
+2
source

Since I do not know the type of panel you are using, you can usually call panel1.Controls.Clear

+1
source
  private void ClearSearchResults() { foreach (Control X in panel1.Controls) { panel1.Controls.Remove(X); } if (panel1.Controls.Count > 0) { ClearSearchResults(); } } 
0
source

Actually, you cannot use Remove because it interrupts the iterator, so something like this would be a simple solution:

 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 with Loop, then use panel1.Controls.Clear()

0
source
  int n; n = panel1.Controls.Count-1; for (int i = 0; i <= n; i++ ) { Control c = panel1.Controls[0]; panel1.Controls.Remove(c); } 
0
source
 while (panel1.Controls.Count != 0) { foreach (Control c in panel1.Controls) { panel1.Controls.Remove(c); } } 

Another way!

0
source

All Articles