views:

203

answers:

5

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 from the labels, but it doesn't work.

+5  A: 

I take it the code isn't removing all the expected controls? This is because you are removing an item from the Control collection, then increment w.

You should called w--; after this.Controls.Remove(...);

If you don't call w--; after removing the control you will step over the control that takes the place of the Control at index w.

Just to add as well, 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 wont be clickable anyway. And if you don't re-add it it'll go out of scope and be collected by the GC.

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

GenericTypeTea
It's better to loop backwards in the first place.
SLaks
It sure is. I just explained why it wasn't working, which I thought was his question.
GenericTypeTea
interesting, wouldn't have got that one +1
Yoda
+5  A: 

Change the for to:

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

Otherwise, you may get an error about modifying the controls. Otherwise, if that doesn't help, and the controls are on the screen, then it would be with your if statement evaluation. Debugging would help fix that.

Brian
A: 

It's doubtful whether CF supports LINQ so you could do next:

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

Alternatively you can use

Form.Controls.Clear();
Yoda
He only wants to remove his TransparentLabel controls. This would remove all controls.
GenericTypeTea
A: 

ctrl.Visible = false;

It fixs the same problem I had. No HTML ouput when the page is rendered.

qiuyl