//以下代码,在Form1_Load中,为所有按钮添加事件,点击后显示此按钮的id
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
try
{
Button b = c as Button;
b.Click += new EventHandler(b_Click);
}
catch
{ }
}
}
void b_Click(object sender, EventArgs e)
{
Button b = sender as Button;
MessageBox.Show(b.Name);
}
给所有的按钮都加上同一个点击事件
private void btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
//这里的btn就是你点击的那个按钮了...你就可以访问它获得你要的东西了
}
private void button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender; //获得当前点击的按钮
MessageBox.Show(btn.Name); //输出id
}
比如一个名叫 btnAdd 的按钮,在它的点击事件中
private void btnAdd_Click(object sender, EventArgs e)
{
MessageBox.show("btnAdd");
}
在事件里写