日期:2014-05-19  浏览次数:20761 次

如何动态插入用户控件
在winform中如何用代码实现动态插入用户控件?

------解决方案--------------------
和插入一般控件一样啊,比如插入按钮就是用
Button newBtn =new Button();
newBtn.ID= "btn1 ";
form1.Controls.Add(newBtn);
------解决方案--------------------
动态插入控件就是把在设计时生成的代码写到运行过程中的方式中。调用的核心方式是
Control.Controls.Add方法。
------
如果是更高级一点,需要动态加载dll,那可以参考下面。
------------------------------------------------
使用反射生成一个窗体的例子:
Assembly assm = Assembly.LoadFrom( "e:\\WindowsApplication.dll ");
Type TypeToLoad= assm.GetType( "WindowsApplication.Form1 ");

object obj;
obj = Activator.CreateInstance(TypeToLoad);
Form formToShow = null;
formToShow = (Form)obj;
formToShow.Show();

----------------
如果是把窗体作为子控件使用可以是这样:
//WinForm嵌入panel
Form2 form = new Form2();
form.FormBorderStyle = FormBorderStyle.None;
form.TopLevel = false;
this.panel1.Controls.Add(form);
form.Show();
------解决方案--------------------
楼主说的应该是WinForm吧.不是WebForm.


private void button2_Click(object sender, EventArgs e)
{
Button btn = new Button();

btn.Name = "btnTest ";
btn.Text = "button ";
btn.Size = button2.Size;
btn.Location = new Point (0,0);
btn.Click += new EventHandler(btn_Click);

this.Controls.Add(btn);
}

void btn_Click(object sender, EventArgs e)
{

// throw new Exception( "The method or operation is not implemented. ");
MessageBox.Show( "Hi. " ,((Button)sender).Name );
}