【问题标题】:How to load a User Control dynamically from a dll into asp:panel如何将用户控件从 dll 动态加载到 asp:panel
【发布时间】:2015-07-03 16:45:18
【问题描述】:

我有超过 3 个网站。所以我想在这些应用程序之间共享一些常见的用户控件。为此,我创建了一个具有通用用户控件(即登录)和其他一些控件的新 Web 应用程序。然后我使用下面的代码生成我加载到我的其他网站的 ddl:

但我无法像 using Control c = Page.LoadContnrol("contrlname.ascx") 那样使用下面的代码将用户控件从 dll 加载到面板中。

Assembly assembly = Assembly.LoadFrom(pluginPath);
Type controlType = assembly.GetType("ABCCommon.controls.LoginPanel");
object controlss = Activator.CreateInstance(controlType);      

// this section doesn't load the user control from dll into panel

pnlLoginControl.Controls.Add((Control)c);

Assembly plugin = Assembly.LoadFrom(pluginPath);

    Type[] types = plugin.GetTypes();

    foreach (Type t in types)
    {
        if (typeof(UserControl).IsAssignableFrom(t))
        {
            UserControl control = (UserControl)Activator.CreateInstance(t);

            controls.Add(control);
        }
    }

    UserControl c = (UserControl)controls[0];

//此部分不会将用户控件从dll加载到面板中

    this.pnlLoginControl.Controls.Add(c);   

请问有人可以帮忙吗? 谢谢!

【问题讨论】:

    标签: asp.net c#-3.0


    【解决方案1】:

    您必须使用 VirtualPathProvider 来执行此操作。问题是 Controls.Add(c) 期望找到 ascx 文件,但那是在另一个项目中。

    tutorial 解释了要采取的步骤。

    【讨论】:

    • 感谢 Wouter de Kort,是的,这篇文章很有帮助。
    【解决方案2】:

    未在程序集中指定用户控件。用户控件由 .ascx 文件定义,并由 asc.net 在运行时在临时程序集中编译。

    要实例化用户控件,您应该使用方法Page.LoadControl

    【讨论】:

    • 谢谢,您的意思是 Page.LoadContnrol("contrlname.ascx"),但我想从 dll 加载?
    【解决方案3】:

    如果您在项目中添加对 DLL 的引用,并使用接受类型(以及传递给构造函数的任何参数)的重载 LoadControl 方法:

    MyControl ctrl = LoadControl(typeof(MyControl), null); 
    

    第二个参数用于将参数传递给参数化构造函数。

    编辑

    如果这些是自定义服务器控件,只需在项目中添加对 DLL 的引用,然后在使用该控件的任何页面上导入程序集:

    using ABCCommon.Controls;
    

    使用控件:

    LoginPanel loginPanel = new LoginPanel();
    loginPanel.ID = "loginPanel1";
    pnlLoginControl.Controls.Add(loginPanel);
    

    【讨论】:

    • 谢谢詹姆斯,我也使用过这种技术,但它对我不起作用!
    • 怎么没用?发生了什么?它没有显示或没有编译?
    • 不是用户控件,我也包含了引用,并将控件返回到此处的对象:ChilliCommon.controls.LoginPanel abc = (ChilliCommon.controls.LoginPanel)LoadControl(typeof(ChilliCommon.controls.LoginPanel), null); 但在登录用户控件上返回空按钮和文本框
    • 您没有在 web.config 中注册程序集并在标记中声明控件是否有原因?
    • 我不明白您的意思,请您详细说明一下:“并在标记中声明控件”?
    猜你喜欢
    • 2010-12-18
    • 2023-03-09
    • 1970-01-01
    • 2011-09-06
    • 2011-06-20
    • 2011-05-17
    相关资源
    最近更新 更多