e.CommandArgument for asp button is not working

2019-01-26 03:25发布

I am developing a asp.net application using C#. I created an .aspx page and placed four buttons on different locations on the page. On server side, I want to use just one click event for all four buttons.

Here is my code:

aspx page

<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条回答
何必那么认真
2楼-- · 2019-01-26 04:13

Use

OnCommand = 

and

protected void allbuttons_Click(object sender, CommandEventArgs e) { }
查看更多
劫难
3楼-- · 2019-01-26 04:22

@Tejs is correct in his comment, looks like you want something like this:

protected void allbuttons_Click(object sender, EventArgs e)
{
    var argument = ((Button)sender).CommandArgument;
}
查看更多
闹够了就滚
4楼-- · 2019-01-26 04:22

You can assign command-text to your buttons as follows:

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;
    }
}
查看更多
走好不送
5楼-- · 2019-01-26 04:25

Actually you don't need to pass the CommandArgument at all to know which button you pressed. You can get the ID of the button like below:

string id = ((Button)sender).ID;
查看更多
登录 后发表回答