gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:59:08 25 4
gpt4 key购买 nike

我有一个程序,我在其中动态添加控件。控件类型基于 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

关于c# - 如何在表单中动态添加自定义控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47482637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com