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 us
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.
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.
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);