How to create an event handler for multiple buttons?

社会主义新天地 提交于 2019-11-29 16:34:26

Subscribe same handler for all buttons and use sender to get button which raised event:

void Button_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;
    // use Name or Tag of button
}

If your buttons named as alphabets A..Z then you can just use button.Name to get letter. If buttons have names like buttonA...buttonZ you can get substring from button.Name to get related letter (or button.Name.Last()). If buttons have names not related to alphabets, then you can use Tag property of button to set and get letter which is assigned to each button.

Monah

Assume you have button1, button2, button3. You can point all the buttons click event to the same method on the design page:

or in the load event

button1.Click+=button_Click;
button2.Click+=button_Click;
button3.Click+=button_Click;

and you write the method

private void button_Click(object sender, EventArgs e)
{
    var button=sender as Button;
    // your code

}

Something like

private void Button_Click(object sender, EventArgs e)
    {
        Button b = (Button) sender;
        //button name
    }

msdn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!