簡體   English   中英

動態加載的用戶控件未呈現

[英]Dynamically loaded user control not rendering

我試圖使用戶控件像插件一樣工作:從用戶的選擇中動態加載(使用反射)。 單擊按鈕后,我可以看到UI進行了調整,以表明用戶控件已被加載,但是控件本身無法。 我什至使用過viewstate,但仍然看不到控件。

請在下面找到我的代碼:

protected void Page_Load(object sender, EventArgs e)
    {
        //the scenario should be: a user clicking a button and from there, 
        //loads the control just below it, but still in the same page.
        if (Page.IsPostBack)
            LoadUserControl();

        //(a)I also tried to put in a ViewState but still nothing happens.
        //if (ViewState["UserControl"] != null)
        //{
        //    UserControl uc = (UserControl)ViewState["UserControl"];
        //    pnlReportControl.Controls.Add(LoadControl());
        //}

    }

//supposedly done after a button click
private void LoadUserControl()
    {
        enrolmentReports = string.Concat(Server.MapPath("~"), enrolmentDll);

        assembly = Assembly.LoadFrom(enrolmentReports);

        Type type = assembly.GetType("TZEnrollmentReports.EnrollmentUserControl");

        enrolmentMethodInfos = type.GetMethods();

        //also tried this way but also didn't work
        //Page.LoadControl(type, null);

        UserControl uc1 = (UserControl)LoadControl(type, null);

        pnlReportControl.Controls.Add(uc1);

        //(a)
        //ViewState["UserControl"] = uc1;
    }

請幫忙。 這只是整個復雜過程的第一步。 我仍然必須從該報告中獲取數據集。 但是我想我將其留給另一個線程。

謝謝!

我相信這是設計LoadControl(Type, Object) ,它沒有返回您所期望的LoadControl(Type, Object)

如果將其更改為使用LoadControl("PathOfControl")則應該可以使用。

有關更多信息,請參見此SO Q&A。 使用LoadControl方法動態加載UserControl(類型,對象[])

一個可以幫助您解決此問題的建議是稍微改變一下方法。 通常,在開發可插拔系統時,會將可插拔性基於某些接口。 在您的情況下,我將創建一個接口IPlugin ,該接口定義一種方法,例如CreateUI和其他方法,以某種通用形式在內部檢索由自定義控件管理的數據。

這樣,您將把正確地創建UserControl並將其返回給調用方(您的頁面)的責任委托給插件實現(您的自定義控件)。 通過反射加載插件實現后(類似這樣):

Assembly pluginDLL = Assembly.Load(System.IO.File.ReadAllBytes(fullPath));
Type pluginType = pluginDLL.GetType(step.PluginClass);
IPlugin plugin = (IPlugin)Activator.CreateInstance(pluginType);

那么您可以在頁面上加載控件:

pnlReportControl.Controls.Add(plugin.CreateUI());

嘗試在您的page_load方法中替換以下代碼

if (Page.IsPostBack) LoadUserControl(); if (!Page.IsPostBack) LoadUserControl();

暫無
暫無

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

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