Remove all controls in the flowlayout panel in C #

I create a flow layout panel, each element of which represents a room. I want to reboot the entire room by deleting all the controls in the panel and adding new controls.

I used:

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

but some controls cannot be deleted.

I tried to find a solution on the Internet, but did not find it anywhere.

Did any body help?

+4
source share
4 answers

This is because you are removing controls from the same list that you iterate. Try something like this

 List<Control> listControls = flowLayoutPanel.Controls.ToList(); foreach (Control control in listControls) { flowLayoutPanel.Controls.Remove(control); control.Dispose(); } 

Maybe not so, but you get the point. Get them in the list and then delete them.

+8
source

According to MSDN, you can clear all ControlCollection controls (e.g. FlowLayoutPanel ) by calling the Clear() method . For instance:

 flowLayoutPanel1.Controls.Clear(); 

Know: just because items are removed from collections does not mean that handlers have disappeared and they need to be disposed of properly so that you do not encounter memory leaks.

+5
source

Note: this is a working solution based on the previous comment, therefore loans to this 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(); } 

This is probably a better / cleaner way to do this, but it works.

+2
source

If you are looking for a simple and quick solution. Here it is.

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

Source: https://habr.com/ru/post/1437098/


All Articles