I have three buttons each calling btn_Clicked on their onClick event. In code behind I want to get the ID of the button that caused postback. I know I can assign each button to call a different method but I would like to learn a bit of ASP.Net. Also tell me which method is more efficient? Calling different methods on different button clicks or calling the same method (if the functionality of each button is same).
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Cast 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
on different button clicks or calling the same method (if the
functionality of each button is same).
If the functionality is same then it’s better to have a single event, since you don’t have to replicate 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")
{
}
}
Method 2
Check whether the sender argument of your callback method is the same reference as the button your are interested in.
Button button1;
Button button2;
void OnClick(object sender, RoutedEventArgs args)
{
Button button = sender as Button;
if (button == button1)
{
...
}
if (button == button2)
{
...
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0