c# 动态创建系统的控件或类,这些类名或控件都是未知,只知道类的名称。要怎么写?
如知道 System.Windows.Forms.TextBox
或 System.Windows.Forms.Label
这样写 创建不出。
Activator.CreateInstance(System.Type.GetType(textBox1.Text));
c# 动态创建系统的控件或类,这些类名或控件都是未知,只知道类的名称。要怎么写?
如知道 System.Windows.Forms.TextBox
或 System.Windows.Forms.Label
这样写 创建不出。
Activator.CreateInstance(System.Type.GetType(textBox1.Text));
收起
示例如下:
private void Form2_Load(object sender, EventArgs e)
{
var labelType = typeof(Control).Assembly.GetType("System.Windows.Forms.Label");
var lb = (Control)Activator.CreateInstance(labelType, true);
lb.Location = new Point(10, 15);
lb.Width = 50;
lb.Text = "用户名";
Controls.Add(lb);
var textBoxType = typeof(Control).Assembly.GetType("System.Windows.Forms.TextBox");
var tb = (Control)Activator.CreateInstance(textBoxType, true);
tb.Location = new Point(60, 10);
tb.Width = 200;
Controls.Add(tb);
}
运行结果:
报告相同问题?