Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing labels which name starts with a certain text

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]);
        }
    }
}
like image 733
Illia Avatar asked Nov 04 '25 13:11

Illia


1 Answers

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

like image 193
Tim Schmelter Avatar answered Nov 06 '25 03:11

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!