首页 > 代码库 > C# 动态事件示例

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=0; i<10; 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# 动态事件示例