2012-05-16 43 views
0

我試圖做一個像插件一樣的usercontrol工作:從用戶的選擇動態加載它(使用反射)。當我點擊按鈕後,我可以看到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; 
    } 

請幫助。這只是整個複雜過程的第一步。我仍然需要從該報告中獲取數據集。但我想我會把它留給另一個線程。

謝謝!

+0

如果您嘗試調試你的代碼,是'uc1'正確實例化?它是您希望顯示的用戶控件嗎? – themarcuz

+0

其實是的。當我嘗試調試代碼時,它顯示了我期望的usercontrol和其中的所有方法。 UI甚至改變以適應用戶控制的假定高度。 – iceheaven31

+1

你確定問題不在usercontrol本身上嗎?也許它不能正確生成html。你是否試圖以硬編碼的方式將它加載到頁面上(所以不要動態加載),以驗證它是否正確顯示? – themarcuz

回答

-2

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

+1

他談到點擊按鈕後顯示控件,因此評估「Page.IsPostBack」是正確的。即使我希望它只是一個簡單的例子,因爲我會在點擊事件處理程序中執行它... – themarcuz

1

有人建議,可以幫助你解決這個問題,是改變一點點的做法。通常開發一種可插拔系統,可以將可插拔性基於一些接口。在你的情況下,我會創建一個接口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());