C# 如何检测在后面的代码中单击了哪个按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13853028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:58:46  来源:igfitidea点击:

How to detect which button was clicked in code behind?

c#asp.netbutton

提问by Huzaifa Qamer

I have three buttons each calling btn_Clickedon their onClickevent. 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).

我有三个按钮,每个按钮都在调用btn_Clicked它们的onClick事件。在后面的代码中,我想获取导致回发的按钮的 ID。我知道我可以分配每个按钮来调用不同的方法,但我想学习一些 ASP.Net。还告诉我哪种方法更有效?在不同的按钮点击上调用不同的方法或调用相同的方法(如果每个按钮的功能相同)。

采纳答案by Habib

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

回答by ceyko

Check whether the senderargument 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)
    {
        ...
    }
}