C#不处置的控制就像我告诉它 [英] C# Not Disposing controls like I told it to

查看:109
本文介绍了C#不处置的控制就像我告诉它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Panel控件。和内面板用户可添加组合框的,文本框的标签等,并围绕之类的东西拖他们,还有我的窗体上的删除按钮,如果他们点击它,它会删除该面板内的所有控件。但是这个代码:

 的foreach(在panel.Controls控制控制)
{
control.Dispose( );
}



...不能正常工作。它并不总是处置面板内的所有控件。有时候,摆脱他们大多数人的,有时不仅摆脱一两个。有时候,所有,但1配置。 ?WTF



编辑:



下面是我使用的控件添加到面板的代码:

 的button1_Click(对象发件人,EventArgs五)
{
文本框TBOX =新的TextBox();
tbox.Multiline = TRUE;
tbox.IsAccessible = TRUE;

panel.Controls.Add(TBOX);
}


解决方案

一个简单的方法来删除所有您的控件是做到这一点:

  panel.Controls.Clear(); 



编辑:感谢彼得和保罗,只调用清除()之类因为控件没有设置,这将导致内存泄漏,所以这不是一个好的做法。


I have a Panel control. And inside the panel users can add combobox's, textbox's labels etc and drag them around and stuff, and there's a Delete button on my form where if they click it, it will delete all controls inside that panel. BUT this code:

foreach( Control control in panel.Controls )
{
     control.Dispose();
}

... Does not work properly. It doesn't always Dispose of ALL the controls inside the panel. Sometimes it gets rid of most of them, sometimes it only gets rid of one or two. Sometimes all but 1 are Disposed. WTF?

EDIT:


Here is the code I use to add the controls to the Panel:

button1_Click(object sender, EventArgs e)
{
    TextBox tbox = new TextBox();
    tbox.Multiline = true;
    tbox.IsAccessible = true;

    panel.Controls.Add(tbox);
}

解决方案

A simpler way to delete all your controls is to do this:

panel.Controls.Clear();

Edit: thanks to Pieter and Paolo, just calling Clear() like this will leak memory since the controls are not disposed, so this is not a good practice.

这篇关于C#不处置的控制就像我告诉它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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