在Asp.net中加载动态控件(Asp Page Lifecyle)

时间:2012-07-31 22:42:58

标签: c# asp.net

我有一个加载用户控件的功能,它看起来像这样:

private void AddPopupControlToPage()
    {
        WidgetConfiguration popupControl = new WidgetConfiguration();
        popupControl = (WidgetConfiguration)LoadControl("~/Docking/Widgets/WidgetConfiguration.ascx");
        popupControl.ID = "PopupControlInput1";
        g_PopupControlId = popupControl.ClientID;
        popupControl.Attributes.Add("width", "150px");
        Form.Controls.Add(popupControl);
    }

我有下拉菜单允许我根据选择的模板更改页面布局。我应该能够从任何模板(页面)按下弹出控件。根据我在这里阅读的内容http://msdn.microsoft.com/en-us/library/ms178472.aspx我应该能够在Page_PreInit事件中加载我的控件,但是在那时没有加载表单我得到一个空引用错误。关于我应该如何/在哪里加载弹出控件并将其保留在任何选定页面上的任何想法?

1 个答案:

答案 0 :(得分:2)

你应该加载一个控件,总是覆盖CreateChildControls方法

这样的东西
protected override void CreateChildControls()
    {
        base.CreateChildControls();
        //now load your control here
    }