简体   繁体   English

如何检测代码背后点击了哪个按钮?

[英]How to detect which button was clicked in code behind?

I have three buttons each calling btn_Clicked on their onClick event. 我有三个按钮,每个按钮在他们的onClick事件上调用btn_Clicked In code behind I want to get the ID of the button that caused postback. 在后面的代码中我想获得导致回发的按钮的ID。 I know I can assign each button to call a different method but I would like to learn a bit of ASP.Net. 我知道我可以分配每个按钮来调用不同的方法,但我想学习一点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). 在不同的按钮单击上调用不同的方法或调用相同的方法(如果每个按钮的功能相同)。

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 . 记住DRY原则

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")
    {
    }
}

Check whether the sender argument of your callback method is the same reference as the button your are interested in. 检查回调方法的sender参数是否与您感兴趣的按钮的引用相同。

Button button1;
Button button2;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM