问题描述
我有一个面板控件.在面板内,用户可以添加组合框、文本框的标签等,然后将它们四处拖动等等,我的表单上有一个删除按钮,如果他们点击它,它将删除该面板内的所有控件.但是这段代码:
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();
}
... 不能正常工作.它并不总是处理面板内的所有控件.有时它会去除大部分,有时它只会去除一两个.有时除了 1 之外的所有内容都已处理.跆拳道?
... 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?
这是我用来将控件添加到面板的代码:
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();
感谢 Pieter 和 Paolo,像这样调用 Clear() 会泄漏内存,因为控件没有被释放,所以这不是一个好的做法.
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# 不像我告诉它的那样处理控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!