How to determine which button was pressed in the code?

I have three buttons, each of which calls btn_Clicked in its onClick event. In the code behind, I want to get the ID of the button that caused the postback. I know that I can assign a different method to each button, but I would like to learn a little ASP.Net. Also tell me which method is more efficient? Calling different methods with different button presses or calling the same method (if the functionality of each button is the same).

+7
source share
2 answers

Pass the sender object to the button, and then you can get all the properties.

 Button clickedButton = (Button)sender; 

Also tell me which method is more efficient? Calling different methods with different button presses or when calling the same method (if the functionality of each button is the same).

If the functionality is the same, then it is better to have one event, since you do not need to copy the code. Remember the DRY principle.

Consider the following example:

 protected void Button1_Click(object sender, EventArgs e) { Button clickedButton = sender as Button; if (clickedButton == null) // just to be on the safe side return; if (clickedButton.ID == "Button1") { } else if(clickedButton.ID == "Button2") { } } 
+20
source

Check if the sender argument of your callback method is the same link as your button.

 Button button1; Button button2; void OnClick(object sender, RoutedEventArgs args) { Button button = sender as Button; if (button == button1) { ... } if (button == button2) { ... } } 
+3
source

All Articles