C# this.Controls.Remove 问题
这段代码有什么问题?
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();
}
}
}
我想清除屏幕上的标签,但它不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将 for 更改为:
否则,您可能会收到有关修改控件的错误。否则,如果这没有帮助,并且控件在屏幕上,那么它将与您的 if 语句评估有关。调试将有助于解决这个问题。
Change the for to:
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.
我认为代码没有删除所有预期的控件?这是因为您要从 Control 集合中删除一个项目,然后递增 w。
您应该在
this.Controls.Remove(...);
之后调用w--;
如果您不调用
w--;
删除该控件后,您将跨过取代索引 w 处的控件的控件。还要补充一点,您真的需要调用以下内容吗?
当您删除控件时,它将变得不可见并且无论如何都无法单击。如果您不重新添加它,它将超出范围并被 GC 收集。
为了满足批评者的要求,正确的做法应该是通过 ControlCollection 向后工作。 Brian 在他的答案中对此进行了介绍。
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--;
afterthis.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?
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.
怀疑 CF 是否支持 LINQ,因此您可以执行下一步:
It's doubtful whether CF supports LINQ so you could do next:
ctrl.Visible = false;
它解决了我遇到的同样的问题。呈现页面时没有 HTML 输出。
ctrl.Visible = false;
It fixs the same problem I had. No HTML ouput when the page is rendered.