Solved

Order of execution of page_load etc etc

Posted on 2004-10-22
511 Views
Last Modified: 2007-12-19
Hi there,

I wanted to just ask a quick question...

I notice in asp.net in visual studio i have a number of methods i.e. Page-Load, Oninit, Intializecomponent etc

Currently I building all my app (well the initializing bit)  in page_load i.e. filling variables, binding data to data bound objects etc..

I wanted to know the order of execution for Page_load, oninit, initializecomponent etc etc ... which one executes first??

Would I be better in separating things into Methods i.e. BindDatabase, InitialiseSearchForm and call these from the Page-Load or other method??

Then I was looking at the component at notice there are some remarks (defaults) put in my microsoft

            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>

So i thought it a bit strange, does microsoft not want us adding details to Oninit, Initializecomponent???? Just interested really, i wanted to use them. Is it the norm to use these???

I know page_load is called everytime the page is loaded i.e even on a postback, when are oninit and intializecomponent called?

anyway I wrote a small app, its a search routine that basically should display some dropdownlists, textboxes etc, there is a button called Advanced Search which if I press it, then more dropdownlists and textboxes would be displayed ... and the .text of Advanced Search would now change to simple search, i.e. Press it and we refer to simple search..

When the page loads initially I wanted a way of setting a variable (session) to equal "simple" - for example (not a real world example)... and then when the button is pressed it can change the variable to "advanced" and visa versa... basically so I can keep track of it..

I can't put the initilization of the variable in the page_load otherwise everytime the page would load it would reinitialize it to "simple", so i was wondering if i could use Onit, or initializecomponent?

Anyway I just wanted to insight into this

Thanks

Ian
0
Question by:ianinspain
    15 Comments
     
    LVL 17

    Expert Comment

    by:AerosSaga
    0
     
    LVL 17

    Expert Comment

    by:AerosSaga
    basically page_load should handle all beginning of page logic.  You can expose the mentioned events if you need to for some reason, but typically they are not used unless performing some custom rendering of dynamic controls, etc.

    Aeros
    0
     
    LVL 17

    Accepted Solution

    by:
    A page that wants to handle a certain event should explicitly register an appropriate handler. However, for backward compatibility with the earlier Visual Basic programming style, ASP.NET also supports a form of implicit event hooking. By default, the page tries to match special method names with events; if a match is found, the method is considered a handler for the event. ASP.NET provides special recognition of six method names. They are Page_Init, Page_Load, Page_DataBind, Page_PreRender, and Page_Unload. These methods are treated as handlers for the corresponding events exposed by the Page class. The HTTP run time will automatically bind these methods to page events saving developers from having to write the necessary glue code. For example, the method named Page_Load is wired to the page's Load event as if the following code was written.

    this.Load += new EventHandler(this.Page_Load);

    The automatic recognition of special names is a behavior under the control of the AutoEventWireup attribute of the @Page directive. If the attribute is set to false, any applications that wish to handle an event need to connect explicitly to the page event. Pages that don't use automatic event wire-up will get a slight performance boost by not having to do the extra work of matching names and events. You should note that all Microsoft Visual Studio® .NET projects are created with the AutoEventWireup attribute disabled. However, the default setting for the attribute is true, meaning that methods such as Page_Load are recognized and bound to the associated event.

    The execution of a page consists of a sequence of stages listed in the following table and is characterized by application-level events and/or protected, overridable methods.

    Table 1. Key events in the life of an ASP.NET page
    Stage       Page Event       Overridable method
    Page initialization       Init       
    View state loading               LoadViewState
    Postback data processing               LoadPostData method in any control that implements the IPostBackDataHandler interface
    Page loading       Load       
    Postback change notification               RaisePostDataChangedEvent method in any control that implements the IPostBackDataHandler interface
    Postback event handling       Any postback event defined by controls       RaisePostBackEvent method in any control that implements the IPostBackEventHandler interface
    Page pre-rendering phase       PreRender       
    View state saving               SaveViewState
    Page rendering               Render
    Page unloading       Unload       

    Some of the stages listed above are not visible at the page level and affect only authors of server controls and developers who happen to create a class derived from Page. Init, Load, PreRender, Unload, plus all postback events defined by embedded controls are the only signals of life that a page sends to the external world.
    Stages of Execution

    The first stage in the page lifecycle is the initialization. This stage is characterized by the Init event, which fires to the application after the page's control tree has been successfully created. In other words, when the Init event arrives, all the controls statically declared in the .aspx source file have been instantiated and hold their default values. Controls can hook up the Init event to initialize any settings that will be needed during the lifetime of the incoming Web request. For example, at this time controls can load external template files or set up the handler for the events. You should notice that no view state information is available for use yet.

    Immediately after initialization, the page framework loads the view state for the page. The view state is a collection of name/value pairs, where controls and the page itself store any information that must be persistent across Web requests. The view state represents the call context of the page. Typically, it contains the state of the controls the last time the page was processed on the server. The view state is empty the first time the page is requested in the session. By default, the view state is stored in a hidden field silently added to the page. The name of this field is __VIEWSTATE. By overriding the LoadViewState method—a protected overridable method on the Control class—component developers can control how the view state is restored and how its contents are mapped to the internal state.

    Methods like LoadPageStateFromPersistenceMedium and its counterpart SavePageStateToPersistenceMedium can be used to load and save the view state to an alternative storage medium—for example, Session, databases, or a server-side file. Unlike LoadViewState, the aforementioned methods are available only in classes derived from Page.

    Once the view state has been restored, the controls in the page tree are in the same state they were the last time the page was rendered to the browser. The next step consists of updating their state to incorporate client-side changes. The postback data-processing stage gives controls a chance to update their state so that it accurately reflects the state of the corresponding HTML element on the client. For example, a server TextBox control has its HTML counterpart in an <input type=text> element. In the postback data stage, the TextBox control will retrieve the current value of <input> tag and use it to refresh its internal state. Each control is responsible for extracting values from posted data and updating some of its properties. The TextBox control will update its Text property whereas the CheckBox control will refresh its Checked property. The match between a server control and a HTML element is found on the ID of both.

    At the end of the postback data processing stage, all controls in the page reflect the previous state updated with changes entered on the client. At this point, the Load event is fired to the page.

    There might be controls in the page that need to accomplish certain tasks if a sensitive property is modified across two different requests. For example, if the text of a textbox control is modified on the client, the control fires the TextChanged event. Each control can take the decision to fire an appropriate event if one or more of its properties are modified with the values coming from the client. Controls for which these changes are critical implement the IPostBackDataHandler interface, whose LoadPostData method is invoked immediately after the Load event. By coding the LoadPostData method, a control verifies if any critical change has occurred since last request and fires its own change event.

    The key event in the lifecycle of a page is when it is called to execute the server-side code associated with an event triggered on the client. When the user clicks a button, the page posts back. The collection of posted values contains the ID of the button that started the whole operation. If the control is known to implement the IPostBackEventHandler interface (buttons and link buttons will do), the page framework calls the RaisePostBackEvent method. What this method does depends on the type of the control. With regard to buttons and link buttons, the method looks up for a Click event handler and runs the associated delegate.

    After handling the postback event, the page prepares for rendering. This stage is signaled by the PreRender event. This is a good time for controls to perform any last minute update operations that need to take place immediately before the view state is saved and the output rendered. The next state is SaveViewState, in which all controls and the page itself are invited to flush the contents of their own ViewState collection. The resultant view state is then serialized, hashed, Base64 encoded, and associated with the __VIEWSTATE hidden field.

    The rendering mechanism of individual controls can be altered by overriding the Render method. The method takes an HTML writer object and uses it to accumulate all HTML text to be generated for the control. The default implementation of the Render method for the Page class consists of a recursive call to all constituent controls. For each control the page calls the Render method and caches the HTML output.

    The final sign of life of a page is the Unload event that arrives just before the page object is dismissed. In this event you should release any critical resource you might have (for example, files, graphical objects, database connections).

    Finally, after this event the browser receives the HTTP response packet and displays the page.

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/aspnet-pageobjectmodel.asp
    0
     
    LVL 28

    Expert Comment

    by:mmarinov
    Hi AerosSaga,
    here is the life cylce of the controls events
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconControlExecutionLifecycle.asp

    Regards!
    B..M
    0
     

    Author Comment

    by:ianinspain
    Thanks everyone for  coming back to me with informaiton..

    Ok little confused with all that though <grin>..

    So I shouldn't be using OnInit or InitializeComponent Methods unless I reall have to?

    So the first time a page runs then it goes like this OnInit, InitializeComponent, and then Page_Load BUT what about on a postback are the Oninit and InitializeCOmponent still called?

    And I presume to implement a Page_Unload is like this then

    this.Unload += new EventHandler(this.Page_Unload);

    but where did this.Unload come from????

    and then the actual method would be here....

    private void Page_UnLoad(object sender, System.EventArgs e)
    {

    }

    Sorry sound a little dumb,, still learning this language, never knew about handlers <grin>

    Ian
    0
     
    LVL 17

    Expert Comment

    by:AerosSaga
    you should use

    If Not Page.IsPostBack Then
    'do whatever
    End If

    to handle postbacks in the page_load
    0
     
    LVL 17

    Expert Comment

    by:AerosSaga
    in C# I think its


    if (!Page.IsPostBack) {
    }
    0
     

    Author Comment

    by:ianinspain
    Hi aerosSaga,

    Thanks, but I know how to do check if its a post back....

    What i meant was

    So I shouldn't be using OnInit or InitializeComponent Methods unless I reall have to?

    So the first time a page runs then it goes like this OnInit, InitializeComponent, and then Page_Load BUT what about on a postback are the Oninit and InitializeCOmponent still called?

    And I presume to implement a Page_Unload is like this then

    this.Unload += new EventHandler(this.Page_Unload);

    but where did this.Unload come from????

    and then the actual method would be here....

    private void Page_UnLoad(object sender, System.EventArgs e)
    {

    }

    Sorry sound a little dumb,, still learning this language, never knew about handlers <grin>

    Ian
    0
     
    LVL 17

    Expert Comment

    by:AerosSaga
    I'm a VB.NET guy so I'm not sure about that code, but you should always use the load and unload events given a choice the init and render are available, but the reasons to use these are usually very small, unless as I stated before you are performing some custom rendering.  Just forget about Init and render
    0
     
    LVL 17

    Expert Comment

    by:AerosSaga
    so basically init and initialize are for the UI level, and page load is for logic....Get it???
    0
     

    Author Comment

    by:ianinspain
    Hi AerosSaga, yep think I have it now..

    Got a strange puzzling thought for the Page_Unload..when is this triggered??

    When the page is unloaded?? but how does it arrive here is the user has closed the web browser..

    I presume Unload is just to close connections etc and not output anything, as the browser window will have disappeared already?

    Ian
    0
     
    LVL 28

    Expert Comment

    by:mmarinov
    yes, when you submit the page the order is still the same

    the difference in the order is there with the new events ( for example button onclick event )

    about the Unload event - i don't understand your question
    do you mean that the eventhadler is created and you don't know how ?

    B..M
    0
     
    LVL 17

    Expert Comment

    by:AerosSaga
    Page_Unload

    Page_Unload is the counterpart to Page_Init. Just as Page_Init is an event that happens before anything else happens, Page_Unload happens after everything else happens. It is available for you to perform any operation you need to after you are completely finished with the page.

    For instance, imagine that you temporarily needed to create a file on the server during the page's processing. You wouldn't want to leave it there for eternity, especially if the file was unique to each visitor of the web site. You could have loads and loads of files building on your server without any way to get rid of them. But if you were a good boy or girl, you could destroy the file during the page's Page_Unload event and make the server administrator a happy camper.

    Just to be fair and impartial, I don't want to leave out showing you the structure of the Page_Unload event. Look familiar?

    please read here Ian
    http://www.peachpit.com/articles/article.asp?p=30182
    0
     

    Author Comment

    by:ianinspain
    cool .. thanks .. awarding points much appreciated

    Ian
    0
     
    LVL 17

    Expert Comment

    by:AerosSaga
    yw

    Aeros
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    With the advent of Windows 10, Microsoft is pushing a Get Windows 10 icon into the notification area (system tray) of qualifying computers. There are many reasons for wanting to remove this icon. This two-part Experts Exchange video Micro Tutorial s…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    931 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now