C # this.Controls.Remove problem

What is the problem with this code?

for (int w = 0; w < this.Controls.Count; w++)
{
    if (this.Controls[w] is TransparentLabel)
    {
        la = (TransparentLabel)this.Controls[w];
        if (la.Name != "label1")
        {
            la.Visible = false;
            la.Click -= new System.EventHandler(Clicked);
            this.Controls.Remove(this.Controls[w]);
            la.Dispose();
         }
     }
}

      

I want to clear the screen of shortcuts but it doesn't work.

+2


a source to share


4 answers


Change the value to:

for (int w = this.Controls.Count - 1; w >= 0; w--)

      



Otherwise, you might get a message that the controls have changed. Otherwise, if it doesn't help and the controls are on the screen, then it will be with the evaluation of your if statement. Debugging will help fix this.

+7


a source


I understand that the code does not remove all expected controls? This is because you are removing the item from the Control collection and then increasing w.

You must call w--;

afterthis.Controls.Remove(...);

If you don't call w--;

after the control is removed, you are navigating through the control that replaces the control at index w.

Just add also, do you really need to call the following?



la.Visible = false;
la.Click -= new System.EventHandler(Clicked);
la.Dispose();

      

When you remove the control, it will become invisible and will not be interactive anyway. And if you don't re-add it, it will go out of scope and be collected by the GC.

And to satisfy critics, the correct way you should be doing this is to work backwards through the ControlCollection. Brian talked about this in his answer.

+6


a source


It is questionable if CF supports LINQ so you can do the following:

this.Controls
  .OfType<TransparentLabel>()
  .Where(c => c.Name != "label1")
  .ToList()
  .ForEach(c => this.Controls.Remove(c));

      

0


a source


ctrl.Visible = false;

It fixes the same problem as me. When the page is rendered, no HTML is rendered.

0


a source







All Articles