0

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?

Edward
  • 7,259
  • 8
  • 60
  • 122

5 Answers5

4

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.

Mor Shemesh
  • 2,426
  • 22
  • 34
2

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.."

user472875
  • 3,045
  • 4
  • 33
  • 67
1

Test the sender parameter of the button click event handler - you'll be able to test which button was the sender.

Jackson Pope
  • 14,225
  • 6
  • 53
  • 80
0

Use a Dictionary using 'sender' as key. The 'value' could be the page to navigate to.

S.C. Madsen
  • 4,826
  • 5
  • 31
  • 48
0

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.

Albin Sunnanbo
  • 45,452
  • 8
  • 67
  • 106