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.
a source to share
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.
a source to share
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.
a source to share