繁体   English   中英

如何在表单中动态添加自定义控件

[英]How to add Custom Control in a form dynamically

我有一个程序,其中controls动态添加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()
    {

    }
 }
}

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

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

因此,在您的情况下,它将是:

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

Type.GetType("namespace.Type")仅在mscorlib.dll或当前正在执行的程序集中存在该类型时才起作用。如果这些都不成立,则应使用system.type.assemblyqualifiedname

https://msdn.microsoft.com/zh-CN/library/system.type.assemblyqualifiedname.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM