asp.net :how to use eventargs for parameter passing on button onclick?

Maddy.Shik picture Maddy.Shik · May 6, 2009 · Viewed 64.2k times · Source

i have seen some code in which people pass parameter through commandParameter Property of web control.then what is use of eventargs.

Answer

Jose Basilio picture Jose Basilio · May 6, 2009

This can be useful if you have the same EventHandler method for different buttons. Example, say your markup looks like this:

<asp:Button ID="button1" runat="server" CommandArgument="MyVal1"
   CommandName="ThisBtnClick" OnClick="MyBtnHandler" />
<asp:Button ID="button2" runat="server" CommandArgument="MyVal2"
   CommandName="ThatBtnClick" OnClick="MyBtnHandler" />

You can have the same event handler for both buttons and differentiate based on the CommandName:

protected void MyBtnHandler(Object sender, EventArgs e)
{
     Button btn = (Button)sender;
          switch (btn.CommandName)
          {
                case "ThisBtnClick":
                    DoWhatever(btn.CommandArgument.ToString());
                    break;
                case "ThatBtnClick":
                    DoSomethingElse(btn.CommandArgument.ToString());
                    break;
           }
}

Source: aspnet-passing-parameters-in-button-click-handler