试图找到控件

时间:2014-02-24 15:54:43

标签: c# asp.net

我想动态地将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 !!

1 个答案:

答案 0 :(得分:4)

您正在通过代码添加控件,它们已经是服务器端控件,您不必添加runat="server"。你找不到它们。

确保在查找之前将它们添加到页面中。