簡體   English   中英

找不到動態添加的UserControl .Net的實例

[英]Cannot find instance of dynamically added UserControl .Net

我有一個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,我需要在預初始化時將控件重新添加到頁面上,但是它是可以添加的控件之一,具體取決於從下拉列表中選擇的選項(也可以動態填充)。 我一直在努力弄清楚如何使這項工作。

您可以嘗試這樣的操作,以根據DropDownList選擇的選項將控件重新添加到Page_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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM