2012-06-14 80 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

您是否曾嘗試將動態控件放在某個僅託管動態控件的容器上,然後將其全部刪除? –