【问题标题】:How to add Custom Control in a form dynamically如何在表单中动态添加自定义控件
【发布时间】:2017-11-25 04:31:34
【问题描述】:

我有一个程序,我在其中动态添加controls。控件类型基于database 中的值。例如,如果Database 中的值为Label,则程序会动态创建控件。

动态创建控件效果很好。我正在使用以下功能:

Type typeFrm = typeof(Form);
Assembly assb = typeFrm.Assembly;
Type controlType = assb.GetType("System.Windows.Forms." + strType);
object obj = Activator.CreateInstance(controlType);
Control control = (Control)obj;
return control;

然后Control ctrl = CreateControl(strCtrlType);

其他代码是设置控件的位置、宽度、高度等。

我的问题是我有一个custom control,如何将它动态添加到表单中?我尝试了上面的功能并更改了行:

Type controlType = assb.GetType("System.Windows.Forms." + strType);

Type controlType = assb.GetType("CustomCtrl." + strType);

但它不起作用。该函数始终返回null

查看示例自定义控件代码。

namespace CustomCtrl
{
public class CButton : Button
 {        
    public CButton() : base()
    {

    }
 }
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    这是从程序集中获取类型的方法。想象一下,您在名为 Some.dll 的 dll 中有一个全名(类名 + 命名空间)SomeNamespace.SomeClass 的类:

    Type type = Type.GetType("SomeNamespace.SomeClass, 
        Some"); // without .dll
    

    所以你的情况是:

    Type type = Type.GetType("CustomCtrl.CButton, 
        DllWhereCButtonIs"); // without .dll
    

    【讨论】:

      【解决方案2】:

      Type.GetType("namespace.Type") 仅在类型存在于 mscorlib.dll 或当前正在执行的程序集中时才有效。如果这些情况不属实,则应使用 system.type.assemblyqualifiedname

      https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx

      【讨论】:

      • 当我尝试Type controlType = assb.GetType("CustomCtrl." + strType).AssemblyQualifiedName; 时出现错误cannot convert from string to System.Type
      • @Zhyke - 他的意思是你应该使用Type.GetType("namespace.Type, assembly.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),而不是Type.GetType("namespace.Type").AssemblyQualifiedName。后者显然不应该工作。
      猜你喜欢
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      相关资源
      最近更新 更多