5

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?

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
I know it's been a few years, but can you expand upon the difference in the timing, if any?
1

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.

Comments

0

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.

Comments

0

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.