Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to an event handler

In the below code, I am defining an event handler and would like to access the age and name variable from that without declaring the name and age globally. Is there a way I can say e.age and e.name?

void Test(string name, string age)
{
    Process myProcess = new Process(); 
    myProcess.Exited += new EventHandler(myProcess_Exited);
}

private void myProcess_Exited(object sender, System.EventArgs e)
{
  //  I want to access username and age here. ////////////////
    eventHandled = true;
    Console.WriteLine("Process exited");
}
like image 699
user476566 Avatar asked Sep 06 '12 05:09

user476566


People also ask

Can you pass arguments to event handler?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

Can the arguments be passed on to the Reactjs event handlers directly or indirectly?

We cannot directly pass the argument to the event handler because, in that scenario, the event handler function would call automatically before you even pressed the button.

How do you pass parameters to a function in addEventListener?

Here is the code: var someVar = some_other_function(); someObj. addEventListener("click", function(){ some_function(someVar); }, false);


2 Answers

Yes, you could define the event handler as a lambda expression:

void Test(string name, string age)
{
  Process myProcess = new Process(); 
  myProcess.Exited += (sender, eventArgs) =>
    {
      // name and age are accessible here!!
      eventHandled = true;
      Console.WriteLine("Process exited");
    }

}
like image 58
ColinE Avatar answered Oct 13 '22 14:10

ColinE


If you want to access username and age, you should create handler which uses custom EventArgs (inherited from EventArgs class), like following:


public class ProcessEventArgs : EventArgs
{
  public string Name { get; internal set; }
  public int  Age { get; internal set; }
  public ProcessEventArgs(string Name, int Age)
  {
    this.Name = Name;
    this.Age = Age;
  }
}

and the delegate

public delegate void ProcessHandler (object sender,  ProcessEventArgs data);
like image 11
Maciek Talaska Avatar answered Oct 13 '22 14:10

Maciek Talaska