Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net OnClick vs Function() Handles buttonName.Click

Tags:

asp.net

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?

like image 677
Erik Ahlswede Avatar asked Jul 06 '09 19:07

Erik Ahlswede


2 Answers

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.

like image 185
bdukes Avatar answered Nov 18 '22 05:11

bdukes


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.

like image 32
John Calsbeek Avatar answered Nov 18 '22 06:11

John Calsbeek