Probably overkill for what you need, but this is a general reflection driven
event binding code.

Object source = GetEventSourceObject();
String eventName = GetNameOfEventOnSource();
Object target = GetObjectToHandleEvent();
String handlerName = GetNameOfMethodToHandleEvent();

Type sourceType = source.GetType();
EventInfo eventInfo = targetType.GetEvent( eventName );
Delegate handler =
        Delegate.CreateDelegate(
                        eventInfo.EventHandlerType,
                        target,
                        handlerName );
eventInfo.AddEventHandler( target, handler );


Russ

-----Original Message-----
From: Unmoderated discussion of advanced .NET topics.
[mailto:[EMAIL PROTECTED] On Behalf Of John Dumais
Sent: Friday, January 28, 2005 1:52 PM
To: [email protected]
Subject: [ADVANCED-DOTNET] Adding an event handler using reflection?


Hello,

I'm trying to create an application that can allow users to extend the menu
by supplying the event handlers in their own libraries.  My first thought
was to use reflection to specify the event handler, something like this...

// The user's assembly has already been loaded and we have created an //
instance of the type the user specifies

MenuItem menuItem = new MenuItem("TextTheUserTellsMe");

// Here's where the problem is...  I'm trying connect the Clieck event //
delegate to the handler by doing this... menuItem.Click +=
(System.EventHandler)Delegate.CreateDelegate(type,
    typeInstance, instanceMethodName);

This last line results in an exception like this...

An unhandled exception of type 'System.ArgumentException' occurred in
mscorlib.dll

Additional information: Type must derive from Delegate.

I think I don't understand something fundamental.  Any suggestions getting
me pointed in the right direction would be appreciated.

[EMAIL PROTECTED]

===================================
This list is hosted by DevelopMentorR  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

===================================
This list is hosted by DevelopMentor�  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to