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?
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();
Does this work for you?
private void ClearSearchResults()
{
panel1.Controls.Clear();
}
Edited to emphasize the CKret comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With