How to create an event handler for multiple buttons?

前端 未结 3 1766
孤街浪徒
孤街浪徒 2020-12-22 03:10

In my C# project, I am creating a Hangman game that has a set of buttons which contains the alphabets from A to Z. All these buttons when clicked will execute the same metho

3条回答
  •  Happy的楠姐
    2020-12-22 03:40

    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.

提交回复
热议问题