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); }
Page_load: The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering.
Page load event guarantees that all controls are fully loaded.
1. Page Request. Page Request is the first step of the page life cycle. When a user request is made, the server checks the request and compiles the pages.
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.
It depends on your requirements.
Page Load : Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data. See Handling Inherited Events.
Prerender :Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost. See Handling Inherited Events.
Reference: Control Execution Lifecycle MSDN
Try to read about
ASP.NET Page Life Cycle Overview ASP.NET
Control Execution Lifecycle
Regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With