c#动态创建的按钮如何添加事件?

c#动态创建的按钮如何添加事件?我用for循环动态创建了一组按钮,定义Button bt = new Button();当写bt.Click += new System.EventHandler ( this.btn_Click )时,EventHandler里面应该怎么写呢?bt_Click不能这么写

动态创建和拖控件代码是一样的,

只是拖控件的话,系统把注册事件的代码自动加上了。

你可以在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的点击事件方法名。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-26
可以按照楼主这样写的,只是在后台中把事件处理程序写完整就行,
protected void btn_Click(object sender,EventArgs e)
{
事件处理程序
}本回答被提问者采纳
第2个回答  2013-09-30
private void btn_Click
(object sender, EventArgs e)
{
//这里写这个按钮的事件。
}
第3个回答  2013-09-30
this.button5.Click += new System.EventHandler(this.button5_Click);

private void button5_Click(object sender, EventArgs e)
{
//这里写这个按钮的事件。
}
第4个回答  2013-09-30
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.
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网