我想动态地将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!
你已经有了一个服务器端控件,你应该可以在FindControl中直接找到它。 – Andrei
FindControl不是递归的,这可能是您遇到的问题:_只有当控件直接包含在指定的容器中时,此方法才会找到控件;也就是说,该方法不会搜索控件中控件的整个层次结构_ http://msdn.microsoft.com/en-us/library/486wc64h%28v=vs.110%29.aspx – BlackICE
当您遇到什么事件时创建此控件并将其添加到控件组?猜测,你在页面生命周期中做得太晚了。 – ThatBlairGuy