Sign in to follow this  
Dark Schneider

[.net] Events with parameters (arguments)

Recommended Posts

Dark Schneider    102
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.

Share this post


Link to post
Share on other sites
Mike.Popoloski    3258
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 )
{
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this