Topic: Usercontrol Lifecycle and Page Lifecycle
Description: Gives the life cycle of user control and page lifecycle together
Default.aspx page with a custom control on it. Here is the log of events:
Control: OnInit
Page: Page_Init
Page: Page_Load
Control: OnLoad
Page: Page_PreRender
Control: CreateChildControls
Control: PreRender
Control: SaveViewState
Control: Render
Here is what happens with a click of the submit button:
Control: OnInit
Page: Page_Init
Control: LoadViewState
Control: CreateChildControls
Control: LoadPostData
Page: Page_Load
Control: OnLoad
Page: Page_PreRender
Control: PreRender
Control: SaveViewState
Control: Render
LoadViewState and LoadPostData are now included in the cycle. The biggest difference is that 'CreateChildControls' now gets called before "Page_Load/OnLoad".
public class MyTextbox : CompositeControl
{
private TextBox _txt;
…
#region Class Properties
public string TextBoxValue
{
get {return (_txt.Text);}
set {_txt.Text=value;}
}
#endregion
protected override void CreateChildControls()
{
_txt = new TextBox();
_txt.ID = "txtTemp ";
_txt.CssClass = this.CssClass;
_txt.Columns = 5;
_txt.MaxLength = 30;
Controls.Add(_txt);
…
}
protected override void Render(HtmlTextWriter output)
{
…
}
}
The issue with CreateChildControls is that if you set 'TextBoxValue' property of the control in 'Page_Load' event of the page - you will get an exception that '_txt' doesn't exist. It does work without any problems if you set that value after the first form submit.
So:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.isPostBack)
myTextbox.Value="Whatever"; //Throws exception
else
myTextbox.Value="Whatever"; //Works fine
}
To fix this problem modify TextBoxValue property as follows
public string Value
{
get
{
EnsureChildControls();
return _txt.Text;
}
set
{
EnsureChildControls();
_txt.Text=value;
}
}