C# 如何一次性处理面板或表单中的所有控件???C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1511047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:18:09  来源:igfitidea点击:

How do I dispose all of the controls in a panel or form at ONCE??? c#

c#controlsdispose

提问by Luiscencio

Possible Duplicate:
Does Form.Dispose() call controls inside's Dispose()?

可能的重复:
Form.Dispose() 是否调用 Dispose() 内的控件?

is there a way to do this?

有没有办法做到这一点?

采纳答案by Charles Bretana

Both the Panel and the Form class have a Controls collection property, which has a Clear() method...

Panel 和 Form 类都有一个 Controls 集合属性,它有一个 Clear() 方法......

MyPanel.Controls.Clear(); 

or

或者

MyForm.Controls.Clear();

But Clear()doesn't call dispose()(All it does is remove he control from the collection), so what you need to do is

Clear()不调用dispose()(它所做的只是从集合中删除他的控制),所以你需要做的是

   List<Control> ctrls = new List<Control>(MyPanel.Controls);
   MyPanel.Controls.Clear();  
   foreach(Control c in ctrls )
      c.Dispose();

You need to create a separate list of the references because Dispose also will remove the control from the collection, changing the index and messing up the foreach...

您需要创建一个单独的引用列表,因为 Dispose 还会从集合中删除控件,更改索引并弄乱 foreach ...

回答by scottm

I don't believe there is a way to do this all at once. You can just iterate through the child controls and call each of their dispose methods one at a time:

我不相信有办法一下子做到这一切。您可以遍历子控件并一次调用一个它们的每个 dispose 方法:

foreach(var control in this.Controls)
{
   control.Dispose();
}

回答by Steven Evers

You don't give much detail as to why.

您没有详细说明原因。

This happens in the Dispose override method of the form (in form.designer.cs). It looks like this:

这发生在表单的 Dispose 覆盖方法中(在 form.designer.cs 中)。它看起来像这样:

protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        components.Dispose();
    }

    base.Dispose(disposing);
}

回答by Joel Coehoorn

You didn't share if this were ASP.Net or Winforms. If the latter, you can do well enough by first calling SuspendLayout()on the panel. Then, when finished, call ResumeLayout().

你没有分享这是 ASP.Net 还是 Winforms。如果是后者,您可以通过首先调用SuspendLayout()面板来做得足够好。然后,完成后,调用ResumeLayout()