动态创建和拖控件代码是一样的,
只是拖控件的话,系统把注册事件的代码自动加上了。
你可以在Form1上拖一个按钮,然后双击(产生一个click事件),
再看Form1.Designer.cs文件中的代码,如下:
//
// button1
//
this.button1 = new System.Windows.Forms.Button();
this.button1.Location = new System.Drawing.Point(131, 73);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//注册事件
this.button1.Click += new System.EventHandler(this.button1_Click);
在for循环中添加button,注意各button的点击事件方法名。
可以按照楼主这样写的,只是在后台中把事件处理程序写完整就行,
protected void btn_Click(object sender,EventArgs e)
{
事件处理程序
}
private void btn_Click
(object sender, EventArgs e)
{
//这里写这个按钮的事件。
}
this.button5.Click += new System.EventHandler(this.button5_Click);
private void button5_Click(object sender, EventArgs e)
{
//这里写这个按钮的事件。
}
private void InitControl()
{
for(int i=0;i<10;i++)
{
Button bt = new Button();
bt.Click += new System.EventHandler ( this.btn_Click )
this.flowlayoutPanel.Controls.Add(btn);
}
}
private void btn_Click(object sender, EventArgs e)
{
// your code here.
}