Reputation: 7424
An application I'm writting in silverlight/c# consists of 13 permanent buttons that when clicked perform a simple navigation to another page.
The problem is my code behind has 13 different event handlers(alot of code) for a nearly identical purpose.
Is there a way to detect which button was pressed so that a single event handler gets fired, and a simple if statement within could determine which page to go to?
Upvotes: 0
Views: 1716
Reputation: 3175
In the designer code of your program, tack on the same event handler for all 13 buttons (look for the code that has += and put the same event handler for all of them).
Notice that the event handler has an object (s) parameter. You can use this parameter as follows:
if(s.Name = "Button1") {//button 1 stuff}
else if (s.Name = "Button2") {button 2 stuff}
etc..
EDIT: should have been s.Name = "Button1, 2, 3, etc.."
Upvotes: 2
Reputation: 47038
If you have lots of code in your event handler you should break that out to a separate method anyway and send the button specific parameters to that method.
But you can still have one event handler if you look at the sender argument.
Upvotes: 0
Reputation: 5246
Use a Dictionary using 'sender' as key. The 'value' could be the page to navigate to.
Upvotes: 0
Reputation: 2890
yes: you can use the same method for all buttons, and use the parameter "sender" as "sender.Name" to get the name of the pressed button.
Upvotes: 4
Reputation: 14640
Test the sender parameter of the button click event handler - you'll be able to test which button was the sender.
Upvotes: 1