e.CommandArgument for asp按钮不起作用

时间:2011-04-15 12:19:22

标签: asp.net commandargument aspbutton

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

这是我的代码:

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 page

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

4 个答案:

答案 0 :(得分:39)

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

protected void allbuttons_Click(object sender, EventArgs e)
{
    var argument = ((Button)sender).CommandArgument;
}

答案 1 :(得分:9)

使用

OnCommand = 

protected void allbuttons_Click(object sender, CommandEventArgs e) { }

答案 2 :(得分:2)

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

string id = ((Button)sender).ID;

答案 3 :(得分: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;
    }
}
相关问题