![](/img/trans.png)
[英]how to add dynamically and remove a user control from a user control in a form
[英]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.