[英]How to add Custom Control in a form dynamically
I have a program wherein I am adding controls
dynamically. 我有一个程序,其中
controls
动态添加controls
。 Control type is based on a value in database
. 控件类型基于
database
的值。 For example if the value in Database
is Label
then the program creates the control dynamically. 例如,如果“
Database
值为“ Label
则程序将动态创建控件。
Creating controls dynamically is working great. 动态创建控件的效果很好。 I am using below function:
我正在使用以下功能:
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;
then Control ctrl = CreateControl(strCtrlType);
然后
Control ctrl = CreateControl(strCtrlType);
Other code is to setup the control location, width, height etc ect. 其他代码是设置控件的位置,宽度,高度等。
My question is I have a custom control
and how will add it to the form dynamically? 我的问题是我有一个
custom control
,如何将其动态添加到表单中? I tried the function above and change the line: 我尝试了上面的功能并更改了行:
Type controlType = assb.GetType("System.Windows.Forms." + strType);
to 至
Type controlType = assb.GetType("CustomCtrl." + strType);
But its not working. 但是它不起作用。 The function always return
null
. 该函数始终返回
null
。
See sample custom control code. 请参阅示例自定义控制代码。
namespace CustomCtrl
{
public class CButton : Button
{
public CButton() : base()
{
}
}
}
Here is how to get the type from an assembly. 这是从程序集中获取类型的方法。 Imagine you have a class with full name (class name + namespace)
SomeNamespace.SomeClass
within a dll named Some.dll
: 假设您有一个全名(类名+名称空间)的类
SomeNamespace.SomeClass
在名为Some.dll
的dll中:
Type type = Type.GetType("SomeNamespace.SomeClass,
Some"); // without .dll
So in your case it will be: 因此,在您的情况下,它将是:
Type type = Type.GetType("CustomCtrl.CButton,
DllWhereCButtonIs"); // without .dll
Type.GetType("namespace.Type")
only works when the type is present in mscorlib.dll or the currently executing assembly.If not of those things is true, you should use system.type.assemblyqualifiedname Type.GetType("namespace.Type")
仅在mscorlib.dll或当前正在执行的程序集中存在该类型时才起作用。如果这些都不成立,则应使用system.type.assemblyqualifiedname
https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx https://msdn.microsoft.com/zh-CN/library/system.type.assemblyqualifiedname.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.