C# 动态事件示例

public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(button_Click);
button2.Click += new EventHandler(button_Click);
button3.Click += new EventHandler(button_Click); } private void button_Click(object sender, EventArgs e)
{
Button tempButton = sender as Button;
if (tempButton != null)
MessageBox.Show(tempButton.Text);
}
/*生成Button的代码*/
for(var i=; i<; i++){
Button dynamicBtn = new Button();
dynamicBtn.Text = string.Format("这是第{0}个按钮", i);
dynamicBtn.Tag = i;
dynamicBtn.Click += new EventHandler(DynamicButtonClick);
Panel1.Controls.Add(dynamicBtn)
}
/*事件处理函数*/

private void DynamicButtonClick(object sender, EventArgs e){
Button currentBtn = sender as Button;
MessageBox.Show(currentBtn.Tag.ToString(), "按钮编号");
}

 

 
上一篇:C++游戏编程(一开篇)


下一篇:如何架设部署V2EX社区/论坛(Google App Engine版)