Adding event handlers dynamically

  • Thread starter Thread starter Keith Patrick
  • Start date Start date
K

Keith Patrick

Maybe I'm missing something obvious, but is there some way to call
EventInfo.AddEventHandler(object, Delegate) but create the delegate
dynamically, but from an instance method, not a static one
(Delegate.CreateDelegate requires a static method passed in)? I tried
Activator.CreateInstance, but it complains that my event handler doesn't
have a ctor.
 
Hey Keith,

A delegate is a type just like any other classes. This means you can use the "new" keyword to create a new delegate object. For example, if you want to register an event handler with the Click event of a button control (using the EventHandler delegate):

Button1.Click += new EventHandler(this.Button1_Click);

By the way, one of the overloads of Delegate.CreateDelegate works for instance methods as well.

Regards, Jakob.
 
Keith,
but from an instance method, not a static one
(Delegate.CreateDelegate requires a static method passed in)?

Check again, some of it's overloads support instance methods.



Mattias
 
Heh, didn't catch the others (was only looking at the one that takes
MethodInfo, since that's the object I had at the time). Thanks!
 
Back
Top