2

I want to access the event handler of a LinkButton's Command event, but in the snippet bellow fieldInfo is null.

LinkButton button = new LinkButton();
button.Command += (s, e) => { };
Type type = button.GetType();
EventInfo[] eventInfos = type.GetEvents(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (EventInfo eventInfo in eventInfos)
    if (eventInfo.Name == "Command")
    {
        // fieldInfo is null
        FieldInfo fieldInfo = eventInfo.DeclaringType.GetField(eventInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
        Delegate delegates = (Delegate)fieldInfo.GetValue(button);
        foreach (Delegate handler in delegates.GetInvocationList())
        {
            eventInfo.RemoveEventHandler(button, handler);
            // or
            eventInfo.AddEventHandler(button, handler);
            // or do whatever with handler
        }
    }

Code snippet was inspired from this.

Why is fieldInfo null ?

Is there another way to get the event handler of a LinkButton's Command event ?

Also Hans Passant sollution does not work on LinkButton using Command as the field name.

Community
  • 1
  • 1
Chris
  • 1,213
  • 1
  • 21
  • 38

1 Answers1

3

Looking at the LinkCommand reference source:

public event CommandEventHandler Command is "magic".

LinkCommand uses the baseclass UI.Control and the events are stored in a protected EventHandlerList Events.

LinkCommand also has a private property called EventCommand, which appears to be used as the indexer for the Events list.

If I'm reading the source correctly, you'll need to extract Events[EventCommand] and cast it to CommandEventHandler like LinkButton does in OnCommand.

This also appears to be a common practice for classes using UI.Control as a base class.

Eris
  • 7,378
  • 1
  • 30
  • 45
  • I don't know why I didn't try `EventCommand` as the field name. Massive fail. Anyway, I just tried it and it works. Awesome! Also I should probably learn to use the source code more (Yay OSS). – Chris Jul 23 '16 at 20:09
  • 1
    @Chris The reference source is not open source. You're allowed to look at it, but think twice before incorporating any part of it in your own software. Much has been open sourced, https://github.com/dotnet/coreclr, https://github.com/dotnet/corefx, https://github.com/aspnet/, but I don't believe WebForms has. –  Jul 23 '16 at 20:40
  • Exactly why I gave an explicitly clear link, instead of quoting it, and explained what to do instead of writing code that may have been similar to the aforementioned reference code. – Eris Jul 23 '16 at 20:42