Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在代码隐藏中检测单击了哪个按钮?_C#_Asp.net_Button - Fatal编程技术网

C# 如何在代码隐藏中检测单击了哪个按钮?

C# 如何在代码隐藏中检测单击了哪个按钮?,c#,asp.net,button,C#,Asp.net,Button,我有三个按钮,每个按钮在其onClick事件上调用btn\u单击的。在代码隐藏中,我想获取导致回发的按钮的ID。我知道我可以指定每个按钮调用不同的方法,但我想学习一点ASP.Net。还告诉我哪种方法更有效?在不同的按钮单击时调用不同的方法或调用相同的方法(如果每个按钮的功能相同)。将发送者对象强制转换到按钮,然后可以获得所有属性 Button clickedButton = (Button)sender; 还告诉我哪种方法更有效?调用不同的方法 在不同的按钮上单击或调用相同的方法(如果 每个按

我有三个按钮,每个按钮在其
onClick
事件上调用
btn\u单击的
。在代码隐藏中,我想获取导致回发的按钮的ID。我知道我可以指定每个按钮调用不同的方法,但我想学习一点ASP.Net。还告诉我哪种方法更有效?在不同的按钮单击时调用不同的方法或调用相同的方法(如果每个按钮的功能相同)。

将发送者对象强制转换到按钮,然后可以获得所有属性

Button clickedButton = (Button)sender;
还告诉我哪种方法更有效?调用不同的方法 在不同的按钮上单击或调用相同的方法(如果 每个按钮的功能相同)

如果功能相同,那么最好只有一个事件,因为您不必复制代码。记住这句话

考虑以下示例:

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

检查回调方法的
sender
参数是否与您感兴趣的按钮相同

Button button1;
Button button2;

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

在事件处理程序中使用sender对象。这让我有点吃惊。我认为==将使用
Object.equals
,这将测试它们是否是相同的引用。这其中哪一部分是不正确的?无论如何,这可能是最好的做法(而且可能是必要的),因此我的编辑:)我会争论这是否是最好的做法,如果您想访问ButtonID,或者与它的属性相关的一些其他信息,该怎么办。您必须像现在一样将对象强制转换为按钮