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

时间:2014-01-06 05:34:32

标签: c# asp.net user-controls

我有 UserControl ,我将其加载到 UpdatePanel 中的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;
}

但是,我得到的只是空。我需要帮助解决这个问题。

AFAIK,我需要在pre-init上将控件重新添加到页面,但它是可以添加的控件之一,具体取决于从下拉列表中选择的选项(也是动态填充的)。我被困在试图找出如何使这项工作。

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的操作,根据Page_Init中选择的选项在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);
}