2014-02-24 37 views
1

我想動態地將runat=server添加到CheckBoxList,以便可以通過FindControl找到它。試圖找到控件

CheckBoxList cbl = new CheckBoxList(); 
cbl.ID = "cbl" + intQuestionCount.ToString(); 

// get choices from choice list 
int intChoiceListId = Convert.ToInt32(detail.ChoiceListID); 
var choiceList = (from cl in _svsCentralDataContext.SVSSurvey_ChoiceListItems 
        where cl.ChoiceListID == intChoiceListId 
        orderby cl.Description 
        select cl); 
cbl.DataSource = choiceList; 
cbl.DataTextField = "Description"; 
cbl.DataBind(); 
cbl.Visible = true; 
cbl.CssClass = "PositionCol3"; 

questionsPanel.Controls.Add(cbl); 

我有兩個遞歸查找防治方法:

private HtmlControl FindHtmlControlByIdInControl(Control control, string id) 
    { 
     foreach (Control childControl in control.Controls) 
     { 
      if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) 
       && childControl is HtmlControl 
       ) 
      { 
       return (HtmlControl)childControl; 
      } 

      if (childControl.HasControls()) 
      { 
       HtmlControl result = FindHtmlControlByIdInControl(childControl, id); 
       if (result != null) 
       { 
        return result; 
       } 
      } 
     } 

     return null; 
    } 

    private WebControl FindWebControlByIdInControl(Control control, string id) 
    { 
     foreach (Control childControl in control.Controls) 
     { 
      if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) 
       && childControl is WebControl 
       ) 
      { 
       return (WebControl)childControl; 
      } 

      if (childControl.HasControls()) 
      { 
       WebControl result = FindWebControlByIdInControl(childControl, id); 
       if (result != null) 
       { 
        return result; 
       } 
      } 
     } 

     return null; 
    } 

屏幕最初是動態創建(如果的IsPostBack!)的基礎上的SQL記錄。在用戶點擊「保存」按鈕後,會顯示該批次後使用FindControl方法。 既不Find控件方法找到我的CheckBoxList!

+1

你已經有了一個服務器端控件,你應該可以在FindControl中直接找到它。 – Andrei

+0

FindControl不是遞歸的,這可能是您遇到的問題:_只有當控件直接包含在指定的容器中時,此方法纔會找到控件;也就是說,該方法不會搜索控件中控件的整個層次結構_ http://msdn.microsoft.com/en-us/library/486wc64h%28v=vs.110%29.aspx – BlackICE

+0

當您遇到什麼事件時創建此控件並將其添加到控件組?猜測,你在頁面生命週期中做得太晚了。 – ThatBlairGuy

回答

4

您正在通過代碼添加控件,它們已經是服務器端控件,您不必添加runat="server"。你沒有找到他們正確的。

確保在查找它們之前將它們添加到頁面。

+0

控件已被明確添加到頁面,因爲它們被顯示。點擊保存時 - 他們似乎不在那裏。 –

+0

@SteveStaple,當你做一個按鈕點擊它會導致一個'回發',並且由於網絡是無狀態的,這些控件將會丟失。你必須保持自己的狀態。你可能會看到[這個問題](http://stackoverflow.com/questions/17589268/dynamically-created-controls-losing-data-after-postback)的進一步的細節和[這個答案](http:// stackoverflow。 com/a/4218690/961113) – Habib

+0

我終於搞定了。我不得不在會話變量中存儲所有動態控件的細節,所以我可以重新創建它們OnInit。系統奇蹟般地設法記住用戶輸入的字段值,即使它不記得字段。 –