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");
}
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.
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.
Here is the code: var someVar = some_other_function(); someObj. addEventListener("click", function(){ some_function(someVar); }, false);
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");
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With