[asp.net] Using Page_Load and Page_PreRender in ASP.Net

I see some people are using Page_Load and Page_PreRender in same aspx page. Can I exactly know why do we need to invoke both the methods in same asp.net page?

Please see the code below,

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            dprPager.ButtonClickPager += new EventHandler(dprPager_ButtonClickPager);

            if (!Page.IsPostBack)
            {
              InitPager();

            }
        }
        catch (Exception ex)
        {

        }

    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        erMsg.Visible = !string.IsNullOrEmpty(lblError.Text);
    }

This question is related to asp.net

The answer is


Page_Load happens after ViewState and PostData is sent into all of your server side controls by ASP.NET controls being created on the page. Page_Init is the event fired prior to ViewState and PostData being reinstated. Page_Load is where you typically do any page wide initilization. Page_PreRender is the last event you have a chance to handle prior to the page's state being rendered into HTML. Page_Load is the more typical event to work with.


The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.


Well a big requirement to implement PreRender as opposed to Load is the need to work with the controls on the page. On Page_Load, the controls are not rendered, and therefore cannot be referenced.


Processing the ASP.NET web-form takes place in stages. At each state various events are raised. If you are interested to plug your code into the processing flow (on server side) then you have to handle appropriate page event.


The major difference between Page_Load and Page_PreRender is that in the Page_Load method not all of your page controls are completely initialized (loaded), because individual controls Load() methods has not been called yet. This means that tree is not ready for rendering yet. In Page_PreRender you guaranteed that all page controls are loaded and ready for rendering. Technically Page_PreRender is your last chance to tweak the page before it turns into HTML stream.