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,346
  • 8
  • 62
  • 123

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,689
  • 1
  • 24
  • 36
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,115
  • 4
  • 37
  • 68
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,520
  • 6
  • 56
  • 80
0

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

S.C. Madsen
  • 5,100
  • 5
  • 32
  • 50
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
  • 46,430
  • 8
  • 69
  • 108