2014-02-24 25 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。系统奇迹般地设法记住用户输入的字段值,即使它不记得字段。 –