Remove all controls in a flowlayoutpanel in C#

前端 未结 4 1209
名媛妹妹
名媛妹妹 2021-02-10 01:45

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

相关标签:
4条回答
  • 2021-02-10 01:48

    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.

    0 讨论(0)
  • 2021-02-10 02:00

    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.

    0 讨论(0)
  • 2021-02-10 02:04

    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.

    0 讨论(0)
  • 2021-02-10 02:11

    If you are looking for an easy and quick solution. Here it is.

    while (flowLayoutPanel.Controls.Count > 0) flowLayoutPanel.Controls.RemoveAt(0);
    
    0 讨论(0)
提交回复
热议问题