Tacit
Tacit

Reputation: 908

Clear dynamic controls from dynamically created panels

I have the following program in winforms: enter image description here

I Want to clear the two buttons you see in the panels.

The code that I have seems to only clear the last button in the last panel. I need to clear all panels. What am I missing here:

 public Form1()
        {
            InitializeComponent();
        }

        Panel pnl1;
        Panel pnl2;
        Button btn;
        private void createPanels(int spacing)
        {
            pnl1 = new Panel();
            pnl1.Location = new Point(5, spacing);
            pnl1.BorderStyle = BorderStyle.FixedSingle;
            pnl1.Size = new Size(85, 93);
            this.Controls.Add(pnl1);

            pnl2 = new Panel();
            pnl2.Location = new Point(91, spacing);
            pnl2.BorderStyle = BorderStyle.FixedSingle;
            pnl2.Size = new Size(85, 93);
            this.Controls.Add(pnl2);

        }

        void addCons()
        {
            btn = new Button();
            btn.Size = new Size(40, 20);
            btn.Location = new Point(5, 5);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            addCons();
            createPanels(5);
            pnl1.Controls.Add(btn);

            addCons();
            createPanels(99);
            pnl1.Controls.Add(btn);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            pnl1.Controls.Clear();
        }

Upvotes: 0

Views: 1662

Answers (1)

keyboardP
keyboardP

Reputation: 69362

The reason only one panel is clearing is because you're reassigning the value of the pnl1 variable each time you call createPanels. Avoid using global Panel variables here and consider storing the panels in a list.

//class level variable
List<Panel> allPanels = new List<Panel>();

//...   

Panel pnl1 = new Panel();
//...panel code
this.Controls.Add(pnl1);
allPanels.add(pnl1);

Panel pnl2 = new Panel();
//...panel code
this.Controls.Add(pnl2);
allPanels.add(pnl2);

//..
private void button1_Click(object sender, EventArgs e)
{
    foreach(Panel p in allPanels) {
        while (p.Controls.Count > 0) p.Controls[0].Dispose();
    }
}

Alternatively, you could iterate through all the controls on the form and get the Panels like that but using a list gives you more control and potentially avoids having to iterate through lots of controls.

Upvotes: 3

Related Questions