0

I'm trying to get the list of events of a BindingSource and is returning null as my code:

// bs is my BindingSource
PropertyInfo propertyInfo = bs.GetType()
    .GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Static | 
        BindingFlags.Instance | BindingFlags.FlattenHierarchy);

EventHandlerList eventHandlerList = propertyInfo
    .GetValue(bs, new object[] { }) as EventHandlerList;

// The following line returns null
FieldInfo fieldInfo = typeof(BindingSource)
    .GetField("AddingNew", BindingFlags.Instance | BindingFlags.FlattenHierarchy | 
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); 

I put all possible BindingFlags but the error persists. What am I doing wrong?

Luana
  • 183
  • 1
  • 2
  • 10
  • 1
    You wrote twice that you get an error, and once that `null` is returned. Which is it? If it's an error, what is the error message? What is the exact declaration of the `AddingNew` field in the `BindingSource` type? Why are you using `typeof(BindingSource)` instead of `bs.GetType()`? Please see http://stackoverflow.com/help/mcve and http://stackoverflow.com/help/how-to-ask – Peter Duniho Dec 02 '14 at 04:29

1 Answers1

0

Found better answer as duplicate AddEventHandler using reflection - use Type.GetEvent.


AddingNew is event, so to manipulate it you need to get corresponding auto-generated methods - "remove_{EventName}" and "add_{EventName}":

var add = typeof(System.Windows.Forms.BindingSource).GetMethod("add_AddingNew");

Proper way use GetEvent:

var adding = typeof(System.Windows.Forms.BindingSource).GetEvent("AddingNew");

See How are events implemented for details on how events are implemented.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • I modified my code like that: var adding = bs.GetType().GetEvent(myEventName); // myEventName is "AddingNew" object eventkey = adding; var eventHandler = eventHandlerList[eventkey] as Delegate; My variable _eventHandler_ is returning null yet. – Luana Dec 02 '14 at 13:22
  • @Luana I don't know what you expect from indexing some random collection with some object... Please debug your code and see what actually present in your collection. Also make sure to read linked articles - events are strange entities and do not match regular fields when viewed via reflection. – Alexei Levenkov Dec 02 '14 at 19:25