Why Page_load ?

When VS.NET generates a webform you get one eventhandler for free :


private void Page_Load(object sender, System.EventArgs e)
{
   // Put user code to initialize the page here
}


Almost all asp.net demo code uses this generated eventhandler to do its thing. But this event does not allways have to be the right moment for your code. A recent post on adding controls at runtime included a quick walkthough of the page life cycle and the many other places your code can hook into.


Considering page load :



  1. Page_load is too late. When adding controls the viewstate is reported to mess up. On_init would have been better.
  2. Page_load is the right moment. After the page is loaded the full context, with session, request(url) and response, is available. A good moment to load some data.
  3. Page_load is too early. Most eventhandlers, like button clicks, are processed after the load. It would be better to wait until the prerender event. At that moment you know all your eventhandlers have done their thing and you can process the results.

Hooking your code into the wrong event can make your code have to go through some strange hoops to work right.


Wouldn’t it have been better if vs.net genereated by default :


private void Page_Load(object sender, System.EventArgs e)
{
   // Put user code here
}


private void Page_Init(object sender, System.EventArgs e)
{
   // Put user code here
}


private void Page_PreRender(object sender, System.EventArgs e)
{
   // Put user code here
}


?


With thanks to Bill.


Peter

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Stefano Demiliani

    I agree with you… better!