23

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

Maddy.Shik
  • 6,609
  • 18
  • 69
  • 98
  • Possible duplicate of [Can someone please explain to me in the most layman terms how to use EventArgs?](http://stackoverflow.com/questions/1778952/can-someone-please-explain-to-me-in-the-most-layman-terms-how-to-use-eventargs) – Toadfish Apr 17 '16 at 08:14

3 Answers3

53

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

Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
  • I guess I don't understand why a regular function call wouldn't work. I can call a function with empty arguements, I can call a function and pass a variable to it, but I can't say "myfunction(\"option1\")" – jfa Jan 30 '16 at 18:31
6

Various Button type controls in .NET have an OnCommand event as well as an OnClick event. When using the OnCommand event you have additional parameters you can apply to the Button such as CommandName and CommandArgument. These can then be accessed in the CommandEventArgs.

It is useful in places where you want to assign the same method to multiple buttons and use the CommandName and CommandArgument parameters to indicate what functionality clicking that button will produce.

AlexB
  • 7,302
  • 12
  • 56
  • 74
Robin Day
  • 100,552
  • 23
  • 116
  • 167
5

The EventArgs class is a base class. Other web methods use other Event args.

e.g. a LinkButton has an OnClick event with a default EventArgs parameter, but it also has an OnCommand event that takes a CommandEventArgs : EventArgs parameter which has some extra information (namely CommandName & CommandArgument).

The event args base class is just there as a place holder so that all the EventHandlers conform to a similar signature.

Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157