如何在formview项模板中查找控件

时间:2012-11-09 10:36:19

标签: c# asp.net

我试过这个 -

if (FormView1.CurrentMode == FormViewMode.ReadOnly)
{
 DropDownList ddlexpense = (DropDownList)FormView1.Row.FindControl("ddle");
}

在FormView1 DataBound,Init,ItemCreated和一个单独的函数,但我总是得到相同的错误 - System.NullReferenceException:对象引用未设置为对象的实例

1 个答案:

答案 0 :(得分:0)

var cnt = FindControl(formViewTemplate.Row, "controlName");
            var htmlControl = cnt as HtmlControl;
            if (htmlControl != null)
            {//---------------------}
private Control FindControl(Control parent, string id)
    {
        foreach (Control child in parent.Controls)
        {
            string childId = string.Empty;
            if (child.ID != null)
            {
                childId = child.ID;
            }
            if (childId.ToLower() == id.ToLower())
            {
                return child;
            }
            if (child.HasControls())
            {
                Control response = FindControl(child, id);
                if (response != null)
                    return response;
            }
        }

        return null;
    }