有时候多个相同控件的事件若一一处理比较麻烦,并且影响代码美观,这时若在一个统一的方法里处理这些事件是个比较好的选择。ide
以winform上的三个button为例来讲明个人处理方法。this
1,将三个button的click事件绑定到一个事件处理方法上:orm
this.button1.Click += new EventHandler(speakHandler);
this.button2.Click += new EventHandler(speakHandler);
this.button3.Click += new EventHandler(speakHandler);事件
2,处理事件it
private void speakHandler(object sender, EventArgs e)
{
switch ((sender as Button).Text)
{
case "button1":
MessageBox.Show(button1.Text);
break;
case "button2":
MessageBox.Show(button2.Text);
break;
case "button3":
MessageBox.Show(button3.Text);
break;
default:
break;
}
}form
值得注意的是,switch中按钮的判断:到底哪一个按钮引起当前事件。class
总结:这个是十分菜鸟的东西,只为本身记录一下。cli