Dynamic Method names

  • Thread starter Thread starter Jim Witt
  • Start date Start date
J

Jim Witt

Ref: Win2000, .NET 1.1

I want to place series of buttons on a form, my own button class. Would
like to create descriptor array to describe buttons - each needs: text,
x and y position, and method invoked when button clicked.

I've been able to create descriptor with 'text, x, y' just fine (no
brainer). However, I designate button click method as follows:

this.button.Click += System.EventHandler(MyMethod);

public void MyMethod()
{
... code
}

This works fine.


Now, I don't know how to deal with is situation like following, which is
what I need to do:


string bMethod = "MyMethod";

this.button.Click += System.EventHandler(bMethod);


I understand the argument to 'System.EventHandler' cannot be string. But
I don't understand Delegates and Interfaces well enough to know how to
convert string to proper type.

Thanks,

Jim
 
Jim,

You don't need interfaces. Assuming that you have the name of the
method and a reference to the object the method is on, you can create a
delegate using the static CreateDelegate method on the Delegate class.

// Create the delegate for the button click event.
// pobjObject is the object that the method in "bMethod" is on.
EventHandler pobjHandler = (EventHandler)
Delegate.CreateDelegate(typeof(EventHandler), pobjObject, bMethod);

Once you have that, you can add it to the Click event as you would
normally.

Hope this helps.
 
Back
Top