C# 找不到动态添加的UserControl.Net的实例

C# 找不到动态添加的UserControl.Net的实例,c#,asp.net,user-controls,C#,Asp.net,User Controls,我有一个用户控件,我正在将它加载到更新面板中的一个div中。下面是我加载它的代码: controls.IDLControl IdlControl = LoadControl(@"~/controls/IDLControl.ascx") as controls.IDLControl; IdlControl.ClientIDMode = ClientIDMode.Static; IdlControl.ID = "IDLControl"; spGroup.Controls.Clear(); spGro

我有一个用户控件,我正在将它加载到更新面板中的一个div中。下面是我加载它的代码:

controls.IDLControl IdlControl = LoadControl(@"~/controls/IDLControl.ascx") as controls.IDLControl;
IdlControl.ClientIDMode = ClientIDMode.Static;
IdlControl.ID = "IDLControl";
spGroup.Controls.Clear();
spGroup.Controls.Add(IdlControl);
下面是我尝试检索它的实例的代码:

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;
}
但是,我得到的是空的。我需要帮助来解决这个问题


好的,我需要在pre-init上重新将控件添加到页面中,但它是可以添加的控件之一,具体取决于从下拉列表中选择的选项(下拉列表也是动态填充的)。我一直在努力想办法让这一切顺利进行

根据
下拉列表中选择的选项,您可以尝试类似这样的操作,将控件添加回
页面的

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);
}

只有将其添加回
Page\u Init
事件中,才能获得它。您始终可以在
Page_Init
事件的下拉列表中检查所选选项,并决定是否添加用户控件。我复制了代码(几乎),但它不起作用。我的下拉列表在页面_init中为空,因此我无法跟踪在返回前选择的内容。我试着使用hiddenfield,但即使是在回邮时也被屏蔽了。因此,我移动了代码以将下拉列表加载到Page_Init中,并移动了代码以将用户控件重新添加到Page_load中,现在它可以工作了。再次查看,如果用户控件中的数据没有标记为runat=“server”,那么在这个过程中,这些数据现在将丢失。这没什么大不了的,我能轻松处理。谢谢你的帮助。