Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

c# - How to create an event handler for multiple buttons?

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 method. I do not want to create an event handler for each of them one by one. So how do I create a SINGLE event handler for all these buttons?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...