Reputation: 1079
I have found several times that for some reason (for instance, Copy&Paste in the form designer), the Event Handlers assigned to some of the components of a form get lost, i.e., the events are not connected to the correct function in the code of the form.
I would like to check this from either the form code, or from some unit test: ensure that they are not empty at least, or check that they are connected to the correct event handler.
I have seen the questions regarding this, but I can't pass the error The event 'SomeEvent' can only appear on the left hand side of += or -=
. This happens when trying to compare it to null, or even as some other answers suggest, get the list of delegates and then check those.
I'm not trying to mess with the events. On the contrary, I want to ensure that they are correctly set from my unit tests.
Manually subscribing the event handlers to the events of the components in the constructor, for instance, seems like a bad idea to me. They should already be subscribed in the InitializeComponent()
code... and checking if they are or not to subscribe them is exactly the problem I want to solve.
The event handlers I want to check are NOT defined in the Form itself, i.e., they are not my event handlers, but event handlers for the Form, or some of the components. For example, I have a KeyDown event handler for the Form, to check for some shortcuts. Trying to get the InvocationList for such even handler results in the error above.
Upvotes: 0
Views: 841
Reputation: 804
I try to never relay on designer to bound events to code, i prefer to write it in my constructor, calling a "WireEvents()" method if i want to group them togheter
Anyway, if i've understood your question, you could just iterate over the eventhandler attached delegates
any EventHandler / EventHandler<> has a method GetInvocationList() that return the list of attached event delegates so you can use that to do your checks
you can iterate doing something like
if(YourEvent!=null){
foreach (var @delegate in YourEvent.GetInvocationList()){
//do your job
}
}
update: here the link to another answer that address your problem of not being able to call GetInvocationList: https://stackoverflow.com/a/12476529/1716620
Upvotes: 1