Search code examples
asp.netrecursionlifecyclefindcontrol

FindControl not working for dynamically created user control


I am dynamically creating a databound DropDownList control and adding it to placeholder in a databound Repeater control which is a custom user control placed on a page with tabs.

The Id of the DropDownList is set dynamically, and for the generated HTML below it is Comp1A

The control creation and usage works fine, but when I try to find the control recursively, I am always getting null.

Here is the generated HTML:

<select class="formDropDownRating" id="MainContent_ContentPlaceHolder1_TabContainer1_tab1_CE1_Repeater1_Comp1A_0" name="ctl00$ctl00$MainContent$ContentPlaceHolder1$TabContainer1$tab1$CE1$Repeater1$ctl00$Comp1A">
    <option value="5">5 - Strongly Agree</option>
    <option value="4">4 - Agree</option>
    <option value="3">3 - Somewhat Agree</option>
    <option value="2">2 - Disagree</option>
    <option value="1">1 - Strongly Disagree</option>

</select>

To find the control I am calling

target = FindDropDownListControl("Comp1A");

with

see Jeff Atwood's function

protected DropDownList FindDropDownListControl(string controlReference)
{
    Control root = this.Page.FindControl("ctl00"); //the Master page (the root control)
    var ddl = (DropDownList)MyApp.Utility.ExtensionMethods.FindControlRecursive(root, controlReference) as DropDownList; 
    return ddl;
}

Could anyone spot what could be the culprit? How can I get a reference to Comp1A?


Solution

  • I'm not 100% sure, because your code samples don't include how the controls are created, but if my suspicions are correct, the problem is that the control is being created at a point in the Page Lifecycle where it gets wiped out on the postback.

    Where, exactly, is the control being created in the Page Lifecycle? If it's not being ccreated in the right place, or too late in the cycle, then it won't be preserved in the Viewstate on Postbacks.

    If possible, ensure that it's being created in the Page_Init or else manually add it to Page_Init.

    This article explains it more fully.