A method name isn't quite enough... you also need a class name... but assuming the method belongs to the current class (this
) you can use Reflection to do this:
public void ExecuteMethod(string methodName)
{
var methodInfo = this.GetType().GetMethod(methodName);
methodInfo.Invoke(this, new [] {});
}
But you can't assign the above to an event because it is not the right delegate type; most event handlers require a sender
and an EventArgs
. So to make your code work you'd need a little more glue:
Dictionary<string, PictureBox> buttonList = new Dictionary<string,PictureBox>();
string buttonName = "button_file";
buttonList[buttonName].Click += GetHandler(buttonName + "_click");
public Action<object, EventArgs> GetHandler(string handlerName)
{
var methodInfo = this.GetType().GetMethod(handlerName, new Type[] {typeof(object), typeof(EventArgs)});
return new Action<object, EventArgs> (sender, eventArgs) => methodInfo.Invoke(this, new [] {sender, eventArgs});
}
The idea here is that GetHandler
returns an Action
with the right signature (accepting an object and an EventArgs, in that order), which is written as Action<object, EventArgs>
. The GetHandler
method uses reflection to find the right method in the current class, then creates a lambda expression that invokes the method via reflection, passing the arguments as an array.
The above is of course just an example... it would probably be better to store your delegates in a static dictionary that is computed when the page is loaded for the first time.
That being said, if you're looking for event handling flexibility based on a runtime parameter, a better approach is probably to use the Command event, which allows you to pass a string to the handler, which can then take a different action depending on the contents of the string. That way you can hardcode the handler reference but still softcode what it will do.
Dictionary<string, PictureBox> buttonList = new Dictionary<string,PictureBox>();
string buttonName = "button_file";
buttonList[buttonName].Command += buttonList_Command;
buttonList[buttonName].CommandName = buttonName;
protected void buttonList_Command(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case buttonName:
//Do stuff for button_file
break;
case "Foo":
//Do stuff for some other button named foo
break;
default:
throw new InvalidOperationException();
}
}