为什么控件不希望得到删除? [英] Why controls do not want to get removed?

查看:117
本文介绍了为什么控件不希望得到删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图删除包含在我的winform面板中的所有控件,但他们根本不希望得到拆除 - 他们中的一些被删除,其中一些并非如此。我已经尝试2的方法并没有什么:

I am trying to remove all the controls that are contained in my winform panel but they simply do not want to get removed - some of them are removed and some of them not. I have tried 2 approaches already and nothing:


  1. 的foreach

  1. foreach

foreach (Control controlEntry in this.contentsPanel.Controls)
{
    this.contentsPanel.Controls.Remove(controlEntry);
}


  • for

    for (int i = 0; i < this.contentsPanel.Controls.Count; i++)
    {
        this.contentsPanel.Controls.RemoveAt(i);
    }
    


  • 这是怎么回事?

    推荐答案

    您必须留意code这样的,从他们的容器中取出的控制这样会产生不可恢复的资源泄漏。 Controls.Remove /在(),或Controls.Clear()方法由其他海报建议,从集合中删除并重新承载它的停车之窗的控制。一个不可见的窗口,本地窗口可以找到一个热情好客的家庭,而不必被破坏。准备重新托管于另一个父。

    You have to watch out for code like this, removing controls from their container like this produces an unrecoverable resource leak. Controls.Remove/At(), or the Controls.Clear() method as suggested by other posters, removes the control from the collection and re-hosts it to the "parking window". An otherwise invisible window where the native window can find a hospitable home without having to be destroyed. Ready to be re-hosted on another parent.

    这是陷阱,你通常不会将其移动到另一个父。该控件将继续停放窗口上生存,消耗原生Windows资源。垃圾收集器不能恢复这些资源。最终,你的程序会崩溃当Windows拒绝你的工作提供更多的窗口。异常消息会说:错误创建手柄。

    Which is the trap, you typically don't move it to another parent. The control will continue to survive on the parking window, consuming native Windows resources. The garbage collector cannot recover these resources. Eventually your program will crash when Windows refuses to provide more windows to your process. The exception message will say "Error creating handle".

    相反,必须的处置的控制。这也自动删除其母公司控制。正确的code是:

    Instead, you must dispose the control. Which also automatically removes the control from its parent. The proper code is:

     while (contentsPanel.Controls.Count > 0) contentsPanel.Controls[0].Dispose();
    

    或者,如果你发现向后遍历这个有点过于离奇好看。

    Or iterate backwards if you find this a bit too bizarre looking.

    这篇关于为什么控件不希望得到删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆