[.net] Events with parameters (arguments)
I'd like to have Eventhandlers that accept parameters, for example, to store the TextBox values in our data vars I'd like to have something like:
textBox.Leave += new EventHandler(function(ref param));
where 'param' is a class variable and function is something like:
private void function(object sender, System.EventArgs e,ref Type param)
{
param=ConvertToParamType(((TextBox) sender).Text);
}
With this, we only need to assign the eventhandlers like:
textBox1.Leave += new EventHandler(function(ref param1));
textBox2.Leave += new EventHandler(function(ref param2));
textBox3.Leave += new EventHandler(function(ref param3));
textBox4.Leave += new EventHandler(function(ref param4));
with only 1 function, but I don't know how to do this.
See that I put very generic code, functions requires some try-catch and more, but this is not the case, I only want to know how to create EventHandlers with params, because actually I must to repeat the function code for every TextBox because anyone use a different class variable, and I think is repeat work and create a huge code for nothing usefull.
Thanks.
The standard way to do this is to create your own custom event args class and use the EventHandler<> delegate creator, like so:
public class MyClass{ public event EventHandler<MyEventArgs> MyEvent; protected virtual void RaiseMyEvent( MyEventArgs e ) { if( MyEvent != null ) MyEvent( this, e ); }}public class MyEventArgs : EventArgs{ public MyEventsArgs( myParamHere ) { }}MyClass foo = new MyClass();foo.MyEvents += new EventHandler<MyEventArgs>( eventHandler );void eventHandler( object sender, MyEventArgs e ){}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement