Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 516
Maddy.Shik Avatar asked May 06 '09 15:05

Maddy.Shik


3 Answers

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

like image 59
Jose Basilio Avatar answered Oct 23 '22 19:10

Jose Basilio


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.

like image 6
Robin Day Avatar answered Oct 23 '22 17:10

Robin Day


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.

like image 5
Eoin Campbell Avatar answered Oct 23 '22 17:10

Eoin Campbell