【发布时间】:2014-02-24 15:54:43
【问题描述】:
我想将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);
我有2个递归查找控制方法:
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;
}
屏幕最初是基于 SQL 记录动态创建的(如果是 !isPostback)。 FindControl 方法在此批次显示后使用,当用户单击“保存”按钮时。 Find 控件方法都找不到我的 CheckBoxList!!
【问题讨论】:
-
你拥有的是一个服务器端控件,你应该可以使用 FindControl 找到它。
-
FindControl 不是递归的,这可能是您遇到的问题: 只有当控件直接包含在指定容器中时,此方法才会找到控件;也就是说,该方法不会在控件内的控件层次结构中进行搜索 msdn.microsoft.com/en-us/library/486wc64h%28v=vs.110%29.aspx
-
当您创建此控件并将其添加到控件组时,您处于什么事件中?猜测一下,您在页面生命周期中做得太晚了。
-
将 CheckBoxList 类作为 WebControl 还是 HtmlControl?
-
控件是在第一次页面加载时创建的。在单击按钮后,我正尝试将它们连同用户的响应一起读回。