20

我正在使用 C# 开发一个 asp.net 应用程序。我创建了一个 .aspx 页面,并在页面的不同位置放置了四个按钮。在服务器端,我只想对所有四个按钮使用一次单击事件。

这是我的代码:

页面

<asp:Button ID="Button1" runat="server" CommandArgument="Button1" onClick = "allbuttons_Click" />
<asp:Button ID="Button2" runat="server" CommandArgument="Button2" onClick = "allbuttons_Click" />
<asp:Button ID="Button3" runat="server" CommandArgument="Button3" onClick = "allbuttons_Click" />
<asp:Button ID="Button4" runat="server" CommandArgument="Button4" onClick = "allbuttons_Click" />

cs页面

protected void allbuttons_Click(object sender, EventArgs e)
{
    //Here i want to know which button is pressed
    //e.CommandArgument gives an error
}
4

4 回答 4

41

@Tejs 在他的评论中是正确的,看起来你想要这样的东西:

protected void allbuttons_Click(object sender, EventArgs e)
{
    var argument = ((Button)sender).CommandArgument;
}
于 2011-04-15T12:24:25.517 回答
9

利用

OnCommand = 

protected void allbuttons_Click(object sender, CommandEventArgs e) { }
于 2011-04-15T12:29:21.633 回答
2

实际上,您根本不需要传递 CommandArgument 即可知道您按下了哪个按钮。您可以获取按钮的 ID,如下所示:

string id = ((Button)sender).ID;
于 2011-04-15T21:06:11.323 回答
1

您可以将命令文本分配给您的按钮,如下所示:

protected void allbuttons_Click(Object sender, CommandEventArgs e) {
    switch(e.CommandName) {
        case "Button1":
            Message.Text = "You clicked the First button";
            break;
        case "Button2":
            Message.Text = "You clicked the Second button";
            break;
        case "Button3":
            Message.Text = "You clicked Third button";
            break;
        case "Button4":
            Message.Text ="You clicked Fourth button";
            break;
    }
}
于 2011-04-15T12:39:20.390 回答