简体   繁体   English

删除C#中flowlayoutpanel中的所有控件

[英]Remove all controls in a flowlayoutpanel in C#

I'm building a flow layout panel whose each control represents for a room. 我正在构建一个流程布局面板,其中每个控件代表一个房间。 I want to reload all room by removing all controls in the panel and adding new controls. 我想通过删除面板中的所有控件并添加新控件来重新加载所有空间。

I used: 我用了:

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

but some of controls couldn't be removed. 但有些控件无法删除。

I tried to find a solution on the internet but found nowhere. 我试图在互联网上找到解决方案,但无处可寻。

Could any body help? 身体有帮助吗?

That's because you are removing the controls from the same list you are iterating. 那是因为您要从正在迭代的同一列表中删除控件。 Try something like this 尝试这样的事情

List<Control> listControls = flowLayoutPanel.Controls.ToList();

foreach (Control control in listControls)
{
    flowLayoutPanel.Controls.Remove(control);
    control.Dispose();
}

Maybe not like that, but you get the idea. 也许不是那样,但你明白了。 Get them in a list, then remove them. 将它们放入列表中,然后将其删除。

According to MSDN, you can clear all controls from a ControlCollection (such as a FlowLayoutPanel ) by calling the Clear() method . 根据MSDN,您可以通过调用Clear()方法Clear() ControlCollection (例如FlowLayoutPanel )中的所有控件。 For example: 例如:

flowLayoutPanel1.Controls.Clear();

Be aware: just because the items are removed from the collections does not mean the handlers are gone and must be disposed of properly less you face memory leaks. 请注意:仅仅因为从集合中删除项目并不意味着处理程序已经消失,必须妥善处理,减少您面临的内存泄漏。

Note: this is a working solution based on the previous comment, so credits to that person :) 注意:这是一个基于之前评论的工作解决方案,因此归功于该人:)

This worked for me: 这对我有用:

List<Control> listControls = new List<Control>();

foreach (Control control in flowLayoutPanel1.Controls)
{
     listControls.Add(control);
}

foreach (Control control in listControls)
{
     flowLayoutPanel1.Controls.Remove(control);
     control.Dispose();
}

There is probably a better/cleaner way of doing it, but it works. 可能有更好/更清洁的方式,但它的工作原理。

If you are looking for an easy and quick solution. 如果您正在寻找一种简单快捷的解决方案。 Here it is. 这里是。

while (flowLayoutPanel.Controls.Count > 0) flowLayoutPanel.Controls.RemoveAt(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM