20

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
}
Brad
  • 359
  • 5
  • 21
liaqat ali
  • 241
  • 2
  • 3
  • 7
  • 2
    `e.CommandArgument` makes no sense... are you sure you're not referring to `(sender as Button).CommandArgument`? – Tejs Apr 15 '11 at 12:22
  • I just want to know which button is pressed. I want to get command arguments for the button that is pressed. – liaqat ali Apr 15 '11 at 12:24

4 Answers4

41

@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;
}
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
10

Use

OnCommand = 

and

protected void allbuttons_Click(object sender, CommandEventArgs e) { }
AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120
2

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;
gbs
  • 7,196
  • 5
  • 43
  • 69
1

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;
    }
}
Troy Alford
  • 26,660
  • 10
  • 64
  • 82
abhijit
  • 1,958
  • 3
  • 28
  • 39