What is the use of "object sender" and "EventArgs e" parameters? What is the use of "object sender" and "EventArgs e" parameters? asp.net asp.net

What is the use of "object sender" and "EventArgs e" parameters?


EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){   Button btn = sender as Button;   btn.Text = "clicked!";}

Edit:When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked


Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e){    Button btn = (Button)sender;    if(btn.Tag == "Hello")      MessageBox.Show("Hello")    else if(btn.Tag == "Goodbye")       Application.Exit();    // etc.}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e){    if(/* some condition*/)    {       // Cancel this event       e.Cancel = true;    }}