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(th开发者_如何学运维is.Controls[w]);
la.Dispose();
}
}
}
I want to clear the screen from the labels, but it doesn't work.
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.
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.
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));
ctrl.Visible = false;
It fixs the same problem I had. No HTML ouput when the page is rendered.
精彩评论