How can I remove all labels where Name starts with "ToClear"?
I tried this code, but it clears them in two clicks (if there are 26 labels it only removes 13 per click)
private void ClearLabel()
{
foreach (var _object in this.Controls)
{
Console.WriteLine(((Label)_object).Name);
if (_object is Label && ((Label)_object).Name.StartsWith("ToClear"))
{
this.Controls.Remove(this.Controls[((Label)_object).Name]);
}
}
}
I wonder that it does not throw an exception. You are enumerating a collection and inside of this loop you are modifying the source. Instead you should collect the controls to remove and then remove them. Easy and readable with LINQ:
var lblRemove = this.Controls.OfType<Label>().Where(l => Name.StartsWith("ToClear")).ToList();
lblRemove.ForEach(this.Controls.Remove);
Note that it will not find nested controls(like your approach). Therefore you have to use a recursive loop, like this: https://stackoverflow.com/a/65855106/284240
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