c#将usercontrol添加到表单,然后删除

时间:2014-01-25 14:17:52

标签: c# winforms user-controls

在我的Form1上,我有一个带有“自定义”文本的按钮。当您单击自定义时,文本下会出现一个面板(panel2),并使用以下代码将Usercontrol添加到面板中:

    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";
        }
    }

在usercontrol“customizeflowbox”中,我有一个带有文本“Weatherbox”的标签,然后是右边的标签,带有文本“add”。当用户单击“添加”时,它会使用以下代码将用户控件添加到Form1中的flowlayoutpanel:

    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设置为false,因此当您单击该按钮时,它将添加usercontrol并将Settings.Default.weatherboxactive设置为true,并将文本更改为“delete”。

那么我有删除usercontrol的代码,但是它没有用。我尝试了两件事。

首先:

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

但这不起作用,因为如果我也添加一个单独的usercontrol,那么它会删除用户控件而不仅仅是weatherbox。所以我试过了:

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

但它不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您可以按控件类型过滤面板控件,只删除天气控件

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