问题
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?
回答1:
According to MSDN, you can clear all controls from a ControlCollection
(such as a FlowLayoutPanel
) by calling the Clear() method. 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.
回答2:
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.
回答3:
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.
回答4:
If you are looking for an easy and quick solution. Here it is.
while (flowLayoutPanel.Controls.Count > 0) flowLayoutPanel.Controls.RemoveAt(0);
来源:https://stackoverflow.com/questions/12667304/remove-all-controls-in-a-flowlayoutpanel-in-c-sharp