What is the difference between using the OnClick attribute of an ASP.Net Button:
<asp:Button ID="btn" runat="server" Text="New" OnClick="enterFunctionHere" />
vs.
using the event directly in the function:
Sub addNew() Handles btn.Click
Thanks!
UPDATE
If I can do both in VB, which is better? Are they equal?
At the least, in the first option, the generated class for the .aspx page is responsible for wiring up the event handler (and thus, requires the event handler to be Protected
); whereas, in the second option, the codebehind class is responsible for wiring up the event handler (so the event handler can be Private
).
I'm not familiar with how exactly the Handles
keyword is implemented in VB.NET, but it may also affect the timing of the wire-up (I know that wiring up an event in a codebehind's OnInit
method will wire up the method at a different time in the page cycle than wiring it up through the markup, and a few obscure cases where that matters).
I, personally, prefer using the Handles
method (or using +=
in C# in the OnInit
override). This allows the compiler to verify that the methods exist and don't have to be unnecessarily exposed to inheriting classes. Being compiled also helps when using refactoring tools, looking up usages, etc.
There's no appreciable difference. Both are equivalent to using the AddHandler keyword. Using the OnClick
attribute is more compatible with ASP.NET code that might use C#, while using the Handles
keyword is more compatible with Windows Forms VB.NET code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With