Reputation: 11
Hi im practically new to C# i usually program with c++ so please bear with me. I am coding an application and i have 10 buttons, 5 of which which are practically doing the same thing. Currently I have 5 event handlers doing the same thing. How can I change this to a single even handler with if statements. Also my problem is that even though the methods of each button are the same i have some small differences from one to another as described below:
button 1 copared with button 5 button 2 copmpared with button 6 button 3 compared with button 7 and so on
How can i tackle this small difference in each case?
Thankyou so much
Upvotes: 0
Views: 1242
Reputation: 70513
You could set them all to the same handler, get the button that called it, check the id in an if statement and do different actions -- OR -- you could use the much more common refactor that looks like this:
void Button1Action(object sender, EventArgs e)
{
// do stuff for button 1 here
SharedCode();
}
void Button2Action(object sender, EventArgs e)
{
// do stuff for button 2 here
SharedCode();
}
void Button3Action(object sender, EventArgs e)
{
// do stuff for button 3 here
SharedCode();
}
void Button4Action(object sender, EventArgs e)
{
// do stuff for button 4 here
SharedCode();
}
void SharedCode()
{
// do stuff for all buttons
}
Upvotes: 0
Reputation: 23551
button.SomeEvent += SomeHandler
void SomeHandler(object sender, EventArgs e)
{
Button b = (Button)sender; //get the specific button that was pressed
...
}
Use the += operator to add a method to an event and simply add the same method.
Upvotes: 2