Reputation:
I'm a beginner in ASP.NET, just a question on page life cycle:
The MSDN doc says: "Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance", which means, I can also put the programming logic here
protected void Page_PreLoad(object sender, EventArgs e)
{
Label1.Text = "Hello World; the time is now " + DateTime.Now.ToString();
}
so why we always do like
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Hello World; the time is now " + DateTime.Now.ToString();
}
?
Upvotes: 1
Views: 3198
Reputation: 4869
The Page_Load
event handler will properly handle creation of all page controls. Per documentation:
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.
Use the OnLoad event method to set properties in controls and to establish database connections.
...which means, based on your example, the Label1.Text
may get reset by that control's OnLoad
event (depending on the individual control's implementation; I do not know if this is true for Label
control, but it would be in compliance with the documentation if that did happen).
Upvotes: 5