2014-01-25 54 views
1

在我的Form1上,我有一个带有“自定义”文本的按钮。当您单击自定义,面板(是Panel2)出现在文本下方,并且用户控件使用下面的代码添加到面板:c#将用户控件添加到表单,然后删除

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

在用户控件“customizeflowbox”,我有一个标签与文本“Weatherbox”,然后就在右边,一个带有文本“添加”的标签。当用户点击添加,它增加了一个用户控件在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,那么当您单击该按钮,它会添加用户控件,并设置将Settings.Default.weatherboxactive设置为true,并将文本更改为“删除”。

所以然后我有代码删除usercontrol,但它不工作..我已经尝试了两件事。

第一:

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

但是,如果我添加一个单独的用户控件也这并没有因为工作,那么它同时删除用户控件,而不仅仅是weatherbox。所以然后我尝试:

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

但它不工作。我究竟做错了什么?

回答

0

可以通过控制类型过滤面板控制和仅除去天气控制

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