Question

I have a custom Control on which I override the OnInit method.

Update

It seems I need to get the Init event through userControl.GetType().GetEvent("Init"). However the RaiseMethod property of the event is null so I'm unable to raise the event through reflection. Any leads?

Old

I use the following code to load the control (ReflectionUtil invokes the method using reflection):

        Page p = new Page();
        UserControl userControl = (UserControl)p.LoadControl(path);
        p.Controls.Add((Control)userControl);

        //EventArgs eventArgs = new EventArgs();

        //ReflectionUtil.CallMethod((object)p, "OnInit", (object[])new EventArgs[1] { eventArgs });
        //ReflectionUtil.CallMethod((object)userControl, "OnInit", (object[])new EventArgs[1] { eventArgs });

        //Plain Reflection doesn't work either...
        EventArgs eventArgs = new EventArgs();

        MethodInfo initMethod = userControl.GetType().GetMethod("OnInit");
        initMethod.Invoke(userControl, (object[])new EventArgs[1]
          {
            eventArgs
          });

However when I set a breakpoint in my custom control's OnInit method it does not get invoked. Am I missing something here? Any help is greatly appreciated.

Was it helpful?

Solution

OnInit is protected and GetMethod overload you are using only gets public methods.

You could use the overload with the bindingflag NonPublic to get the protected method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top