我有一个程序,我在其中动态添加控件
。控件类型基于 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);
其他代码用于设置控件的位置、宽度、高度等。
我的问题是我有一个自定义控件
,如何将它动态添加到表单中?我尝试了上面的功能并更改了行:
Type controlType = assb.GetType("System.Windows.Forms."+ strType);
到
Type controlType = assb.GetType("CustomCtrl."+ strType);
但是它不起作用。该函数始终返回 null
。
查看示例自定义控件代码。
namespace CustomCtrl
{
public class CButton : Button
{
public CButton() : base()
{
}
}
}
下面是如何从程序集中获取类型。假设您在名为 Some.dll
的 dll 中有一个全名(类名 + 命名空间)SomeNamespace.SomeClass
的类:
Type type = Type.GetType("SomeNamespace.SomeClass,
Some"); // without .dll
所以在你的情况下它将是:
Type type = Type.GetType("CustomCtrl.CButton,
DllWhereCButtonIs"); // without .dll
我是一名优秀的程序员,十分优秀!