日期:2014-05-18  浏览次数:20858 次

如何把字符串变量 转换成控件?
我有3个字符串变量,分别代表   控件类型   控件名称   控件位置左   右

如何动态生成控件实例,


控件类型   控件名称   =   New   控件类型;
上面这行怎么写?

控件名称.Right=10;
控件名称.Left=20;

------解决方案--------------------
参考下:
Type type = Type.GetType( "namespacename.className ");
if (type != null)
{
object obj = Activator.CreateInstance(type);
PropertyInfo pi = type.GetProperty(propertyname);
pi.SetValue(obj, objValue, null);
}

------解决方案--------------------
string aname = "System.Windows.Forms.Button, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ";
Type type = Type.GetType(aname, true);
if (type != null)
{
Control control = Activator.CreateInstance(type) as Control;
control.Text = "testbtn ";
control.Name = "btnqqq ";
control.Click += new EventHandler(control_Click);
control.Left = 100;
control.Top = 100;
this.Controls.Add(control);
}

void control_Click(object sender, EventArgs e)
{
MessageBox.Show( "button ");
}

这是button的一个例子
如果你是别的control
那么把System.Windows.Forms.Button
换成你想要的就可以了
比如TextBox,你就换成System.Windows.Forms.TextBox