Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 980
Johnny Avatar asked Oct 01 '12 03:10

Johnny


People also ask

How to clear FlowLayoutPanel in vb net?

According to MSDN, you can clear all controls from a ControlCollection (such as a FlowLayoutPanel ) by calling the Clear() method. For example: flowLayoutPanel1. Controls.

How to use FlowLayoutPanel in c#?

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.

What is FlowLayout panel?

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.


3 Answers

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.

like image 117
ShooShoSha Avatar answered Oct 05 '22 00:10

ShooShoSha


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.

like image 24
Yoinazek Avatar answered Oct 04 '22 22:10

Yoinazek


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.

like image 42
Fakekiller17 Avatar answered Oct 04 '22 23:10

Fakekiller17