Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetMethod returning null

I have an asp.net web page. This is the class implementing the page:

public partial class _Default : System.Web.UI.Page
    {
        private readonly string delegateName = "DynamicHandler";

        protected void Page_Load(object sender, EventArgs e)
        {
            EventInfo evClick = btnTest.GetType().GetEvent("Click");

            Type tDelegate = evClick.EventHandlerType;

            MethodInfo method = this.GetType().GetMethod("DynamicHandler", 
                BindingFlags.NonPublic | BindingFlags.Instance);

            Delegate d = Delegate.CreateDelegate(tDelegate, this, method);

            MethodInfo addHandler = evClick.GetAddMethod();
            Object[] addHandlerArgs = { d };
            addHandler.Invoke(btnTest, addHandlerArgs);


        }

        private void DynamicHandler(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }

I am trying to hook up an event handler dynamicly. For some reason method remains null and I can't figure out why. I have done this many times before and I can't figure out what I'm missing.

EDIT: I found that this.GetType() returns the type of the page ASP.default_aspx and not the actual type implementing the page. I don't really know how to get around this...

like image 335
Elad Lachmi Avatar asked Dec 08 '22 13:12

Elad Lachmi


1 Answers

For the benefit of anyone else, GetMethod() can also return null if the arguments you passed do not match the arguments of the method you are trying to find. So, for example, if you are trying to find the method:

SomeMethod(int intParam, string stringParam)

You need to pass the parameter types to GetMethod:

type.GetMethod("SomeMethod", new[] { typeof(int), typeof(string) });

Or, if you want to specify special binding flags:

type.GetMethod("SomeMethod", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(int), typeof(string) }, null);
like image 68
AJ Richardson Avatar answered Dec 29 '22 22:12

AJ Richardson