1
votes

On my Form1, I have a button with the text "customize". When you click on customize, a panel (panel2) appears under the text, and a Usercontrol is added into the panel using the following code:

    private void labelcustomize_Click(object sender, EventArgs e)
    {
        if (customize == false)
        {
            customize = true;
            labelcustomize.Text = "Done";
            customizeflowbox customizeflowbox = new customizeflowbox();
            panel2.Controls.Add(customizeflowbox);
        }
        else
        {
            customize = false;
            labelcustomize.Text = "Customize";
        }
    }

In the usercontrol "customizeflowbox", I have a label with the text "Weatherbox", and then just to the right of that, a label with the text "add". When a user clicks add, it adds a usercontrol to a flowlayoutpanel in Form1 using this code:

    private void label2_Click(object sender, EventArgs e)
    {
        if (Settings.Default.weatherboxactive == false)
        {
            Form1 myParent = (Form1)this.Parent.Parent;
            UserControl2 weather = new UserControl2();
            myParent.flowLayoutPanel1.Controls.Add(weather);
            Settings.Default.weatherboxactive = true;
            label2.Text = "delete";
        }
    }

Settings.Default.weatherboxactive is set to false, so when you click that button, it will add the usercontrol and set the Settings.Default.weatherboxactive to true, as well as change the text to "delete".

So then I have the code to delete the usercontrol, but it is not working.. I have tried two things.

First:

        else
        {
            Form1 myParent = (Form1)this.Parent.Parent;
            UserControl2 weather = new UserControl2();
            myParent.flowLayoutPanel1.Controls.clear;
            Settings.Default.weatherboxactive = false;
            label2.Text = "add";
        }

But this did not work because if I add a separate usercontrol also, then it deletes both usercontrols and not just the weatherbox. So then I tried:

        else
        {
            Form1 myParent = (Form1)this.Parent.Parent;
            UserControl2 weather = UserControl2();
            myParent.flowLayoutPanel1.Controls.Remove(weather);
            Settings.Default.weatherboxactive = false;
            label2.Text = "add";
        }

But it is not working as well. What am I doing wrong?

1

1 Answers

0
votes

You can filter panel controls by control type and remove only weather controls

foreach(var weather in myParent.flowLayoutPanel1.Controls.OfType<UserControl2>().ToArray())
{
  myParent.flowLayoutPanel1.Controls.Remove(weather);
}