3

I'm coming from an ASP background and learning ASP.NET. I wanted to know whether AutoEventWireup property wireup the Control events also(like Button_Click) or just the Page events? I read elsewhere in SO that if you set it to TRUE & also provide explicit event handlers, it'll be executed twice, Can you explain why this happens (since there is just 1 handler VS must recognize its already executed)? Can you give Use Cases of setting it to False?

Would appreciate a code sample

Jaison Varghese
  • 1,302
  • 1
  • 13
  • 24

2 Answers2

3

Generally it is set to true, which means you do not need to wireup each even explicitly. You will set it to false when you want to use the same event handler for more than one controls/events. In that case you can explicitly wireup multiple events to single event handler. It controls all events. When you set the property to true and also wireup the events explicitly, .Net will fire the event twice, because delegate will be registered twice.

patil.rahulk
  • 574
  • 1
  • 3
  • 13
1

AutoEventWireup on the Page element works by looking for methods matching an expected signature and naming convention (i.e. Page_<event>). If found, the page framework will call the event-handlers directly before "raising" the event normally. This is why, if you register the event-handlers in code, they are effectively called twice.

This is quite different from how event handlers normally work. If you wrote code to register a handler with the same event twice, it will only be called once per event. This is because the event handlers are essentially a set of delegates and attempting to add a delegate to the same method is a no-op.

The AutoEventWireup behaviour only applies to events raised by the page. You won't get it for other controls, so they should be wired up manually, usually in a Page_Init or Page_Load event.

If you don't use AutoEventWireup (i.e. set it to "false"), you have to wire up the page event handlers yourself to get them to be called. This is what the Visual Studio designer does, since it generates event-registration code for you.

Paul Turner
  • 38,949
  • 15
  • 102
  • 166
  • Thanks for answering most of my queries. Will an event handler be executed if I kept `AutoEventWireup` to be false and forgot to register it using delegates – Jaison Varghese Nov 08 '12 at 14:50
  • Shoudn't it execute atleast once? Since its executing twice when we enable `AutoEventWireup`, (once bcos the signature matches & 2nd as a normal procedure) Is anything missed out. the internal working of calling it twice – Jaison Varghese Nov 08 '12 at 18:30
  • To clarify, there are two mechanisms for getting your page events to fire: Using `AutoEventWireup` and having methods matching the expected patterns and registering event-handlers manually. If you don't use either mechanism, your event-handlers don't get called. – Paul Turner Nov 09 '12 at 09:42