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?
According to MSDN, you can clear all controls from a ControlCollection (such as a FlowLayoutPanel ) by calling the Clear() method. For example: flowLayoutPanel1. Controls.
We can create a FlowLayoutPanel control using the Forms designer at design-time or using the FlowLayoutPanel class in code at run-time (also known as dynamically). To create a FlowLayoutPanel control at design-time, you simply drag and drop a FlowLayoutPanel control from Toolbox to a Form in Visual Studio.
The FlowLayoutPanel control arranges its contents in a horizontal or vertical flow direction. You can wrap the control's contents from one row to the next, or from one column to the next. Alternately, you can clip instead of wrap its contents.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With