Calling an event handler

ALX

Well-known member
Joined
Nov 16, 2005
Messages
249
Location
Columbia, SC
Programming Experience
10+
Many times I've read this advice:
'Do not call an event handler directly.'
... such as 'Button1_Click(Me, Nothing). I'm curious to know why this is generally a programming error. It seems to me like a way to reduce the number of lines of code. What's the down side ?
 
Solution
Event handlers are methods so they can be called like any other. It's a good rule to avoid doing so though, because then you can't do so incorrectly. An event handler expects specific arguments that the object raising the event provides. When people call them directly, they rarely pass the correct arguments. In your example, for instance, you are passing the form as the sender for the Click event of a Button, so that's obviously wrong. That will often make no difference but in some cases it will. Don't do it at all and you can never do the wrong thing in cases where it matters.

Also, one of your primary goals when writing code should ALWAYS be readability. Event handlers exist for a reason: to handle events. If you...

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,579
Location
Sydney, Australia
Programming Experience
10+
Event handlers are methods so they can be called like any other. It's a good rule to avoid doing so though, because then you can't do so incorrectly. An event handler expects specific arguments that the object raising the event provides. When people call them directly, they rarely pass the correct arguments. In your example, for instance, you are passing the form as the sender for the Click event of a Button, so that's obviously wrong. That will often make no difference but in some cases it will. Don't do it at all and you can never do the wrong thing in cases where it matters.

Also, one of your primary goals when writing code should ALWAYS be readability. Event handlers exist for a reason: to handle events. If you use them as regular methods then you're making your code harder to read. If you want to write code to do something then put it in a method that has a name that indicates what that something is. If you call a method named Button1_Click then there is exactly zero indication of what that is actually supposed to achieve.

Also, in the specific case of a Button, you can call its PerformClick method so that it actually does raise a Click event and the event handler is invoked as it should be.
 
Solution
Top Bottom