tags:

views:

385

answers:

4

Hi,

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?

A: 

Both add an event handler. Handles is available in VB.Net, not C#.

Also, you can add an event in code with the AddHandler method of a page.

Tim Hoolihan
A: 

The first one is an example of how pages using c# code behind register the event to the function. This one then needs a method matching the definition.

The second one is the vb.net way of attaching the event to a function.

gjutras
It's not about C# or VB.NET. I think the question is more about the difference between putting OnClick in your ASPX page vs creating event handler in your codebehind file.
SolutionYogi
+4  A: 

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.

bdukes
To elaborate what bdukes wrote, you have to first understand how the ASPX file transforms in to a C# class and how it relates to your code behind class. Once you understand that, you will know that 'practically' there is no difference between the two methods which you have outlined.
SolutionYogi
+1  A: 

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.

John Calsbeek