Page_Init vs OnInit

Between handling the Page_Init event or overriding the OnInit method of a Page, which one is better to use? Thanks.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I had this very question about a year ago, I settled on overridding as opposed to the On_X Events. Here is the article I read covering the pros and cons: http://weblogs.asp.net/infinitiesloop/archive/2008/03/24/onload-vs-page-load-vs-load-event.aspx

Solution 2

Overriding the base type’s method is preferable as a virtual call is simpler and cleaner than creating a delegate attaching an event to a method group.

Also, relying on AutoEventWireup being set to true means that you are introducing overhead into the parsing of your page code as ASP.NET will have to create any delegates for you at execution-time.

Solution 3

Basically there is no difference in this two appoaches.
That’s what is done in OnInit in Page class:

protected internal override void OnInit(EventArgs e)
{
    base.OnInit(e);
    if (this._theme != null)
    {
        this._theme.SetStyleSheet();
    }
    if (this._styleSheet != null)
    {
        this._styleSheet.SetStyleSheet();
    }
}

If we will open base.OnInit we will se that that is the place where Page_Init is fired:

protected internal virtual void OnInit(EventArgs e)
{
    if (this.HasEvents())
    {
        EventHandler handler = this._occasionalFields.Events[EventInit] as EventHandler;
        if (handler != null)
        {
            handler(this, e);
        }
    }
}

So basically there is no difference in these two approaches.
However you need to call base.OnInit in your overriden method if you will choose to use override instead of event.
And another difference is that if you are using override you can run some code just after Theme is applied.

Regards.

P.S. The only thing I recommend is to use the same approach all over the application.

Solution 4

There is a good answer here http://objectmix.com/dotnet/251824-oninit-page_init.html.

http://www.justskins.com/forums/page_init-and-page_load-59045.html has a more indepth answer.

If AutoEventWireup is set to false you need to override OnInit as the Page_Init isn’t automatically available.

Solution 5

OnInit is better because it is on class level initialization while page init can have redundant effect because you have to check if it is a postback or not.

Solution 6

OnX because mostly it is the preferred technique for handling the event in a derived class according to MSDN.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply