Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoEventWireup True Vs False

I am using Visual Studio 2012 professional edition. I do not see any difference over setting "true" versus "false" for AutoEventWireup property in page directive. All the time it is behaving as "true", Meaning - I set "false" and not binding events explicitly, but events are implicitly got bind. Please let me know if I am missing anything.

like image 506
afin Avatar asked Dec 15 '22 13:12

afin


2 Answers

This setting is not about firing an event, but rather about binding handlers to standard page events. Compare these two snippets that illustrate handling Load event.

First, with AutoEventWireup="true":

public class PageWithAutoEventWireup
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Page_Load is called");
    }
}

Second, with AutoEventWireup="false":

public class PageWithoutAutoEventWireup
{
    override void OnInit(EventArgs e)
    {
        this.Load += Page_Load;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Page_Load is called");
    }
}

Load event will be fired by page and handled by your code in both cases. But in second case you have to sign up for the event explicitly, while in first case ASP.NET does everything for you.

Of course, the same goes for other page life-cycle events, like Init, PreRender, etc.

like image 111
Andrei Avatar answered Dec 21 '22 23:12

Andrei


I know this is an old thread, but figured I'd add the following, which recently helped me:

In addition to Andrei's answer, it's worth adding that by setting AutoEventWireup to "true" you run the risk of calling Page_Load() twice each time the page loads. This happened to me. It's explained fully here, from where I copied the following:

Do not set AutoEventWireup to true if performance is a key consideration. When automatic event wireup is enabled, ASP.NET must make between 15 and 30 tries to match events with methods.

Note the following about binding event handlers to events:

  • If you set AutoEventWireup to true, make sure that you do not also manually attach page event handlers to events. If you do, handlers might be called more than one time.

  • Automatic binding is performed only for page events, not for events for controls on the page.

  • As an alternative to binding events to handlers, you can override the Oneventname methods of the page or of controls.

like image 25
RobC Avatar answered Dec 21 '22 23:12

RobC