简体   繁体   中英

Cannot find instance of dynamically added UserControl .Net

I have a UserControl which I am loading into a div which is inside an UpdatePanel . Here is my code for loading it:

controls.IDLControl IdlControl = LoadControl(@"~/controls/IDLControl.ascx") as controls.IDLControl;
IdlControl.ClientIDMode = ClientIDMode.Static;
IdlControl.ID = "IDLControl";
spGroup.Controls.Clear();
spGroup.Controls.Add(IdlControl);

And here is my code for trying to retrieve an instance of it:

controls.IDLControl IdlControl = RecursiveFindControl(this, "IDLControl") as controls.IDLControl;

private Control RecursiveFindControl(Control targetControl, string findControlId) {
    if (targetControl.HasControls()) {
        foreach (Control childControl in targetControl.Controls) {
            if (childControl.ID == findControlId) {
                return childControl;
            }

            RecursiveFindControl(childControl, findControlId);
        }
    }

    return null;
}

But, all I get is null. I need help on figuring this out.

AFAIK, I need to re-add the control to the page on pre-init but it is one of the controls that can be added depending on which option is selected from a drop down list (which also is filled dynamically). I am stuck trying to figure out how to make this work.

You can try something like this to add your control back in the Page_Init based on the option selected in your DropDownList .

protected void Page_Init(Object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (drpYourDropDown.Items.Count > 0 && drpYourDropDown.SelectedItem.Text == "yourOption")
        { 
            AddIDLControl();
        }
    }
}

private void AddIDLControl()
{
    controls.IDLControl IdlControl = LoadControl(@"~/controls/IDLControl.ascx") as controls.IDLControl;
    IdlControl.ClientIDMode = ClientIDMode.Static;
    IdlControl.ID = "IDLControl";
    spGroup.Controls.Clear();
    spGroup.Controls.Add(IdlControl);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM