2012-06-14 37 views
3

我遇到了最近的一个问题,我正在生成关于下拉选择的动态控制。当选择改变时,我必须生成另一组动态控件,删除现有的控件。删除动态控件:清除正在工作,但不能删除

所以我在做这工作不如下:


    private void ClearDynamicControls() 
    { 
     if (adapter != null) 
     { 
      //This has all the controls saved in some dictionary, key as control ID 
      var controls = adapter.GetAllControls().Keys; 
      Control mainControl = (PlaceHolder)this.Form.FindControl("MainContent"); 

      foreach (String controlName in controls) 
      { 
       Control controlToRemove = this.Form.FindControl("MainContent").FindControl(controlName); 
       mainControl.Controls.Remove(controlToRemove); 

      } 
      var controls2 = mainControl.Controls; 
      //clearing the controls in the dictionary 
      adapter.ClearAllControls(); 
     } 


    } 
 

但随着清除类似的代码()方法是工作的罚款。那我该怎么办呢?


    private void ClearDynamicControls() 
    { 
     if (adapter != null) 
     { 
      //This has all the controls saved in some dictionary, key as control ID 
      var controls = adapter.GetAllControls().Keys; 
      Control mainControl = (PlaceHolder)this.Form.FindControl("MainContent"); 
      mainControl.Controls.Clear(); 


      //clearing the controls in the dictionary 
      adapter.ClearAllControls(); 
     } 


    } 
 

通过此代码,所有控件(包括动态和静态)都被删除。那么应该做些什么呢?

请让我知道如果我做错了什么。

我在下拉选择更改事件触发时调用此方法。这些控件添加到表...

+0

你确定foreach循环正在执行吗? –

回答

0

如果你知道你的控件的名字,你可以这样做:

foreach(Control control in Controls){ 
    if(control.Name == "yourControlName"){ 
    Controls.Remove(control); 
    } 
} 

,或者如果你想从例如面板中删除所有控件可以使用:

foreach(Control control in panel.Controls){  
     panel.Controls.Remove(control); 
    } 

希望它有帮助!

+0

感谢您的回复,但问题是我添加动态以及静态控制到表,它通过Clear()函数清除,但不是通过删除函数。我想在下一页加载之前保留静态控件。 – kinshuk4

+0

您是否曾尝试将动态控件放在某个仅托管动态控件的容器上,然后将其全部删除? –