I have composite web server control, which at the moment doesn't perform any actions. My aim is to place inside it child controls beginning with checkbox. I try to do it in the following way:
[DefaultProperty("Text")]
[ToolboxData("<{0}:SubmitImageControl runat=\"server\"></{0}:SubmitImageControl>")]
public class SubmitImageControl : CompositeControl
{
private CheckBox _checkBox;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
protected override void CreateChildControls()
{
_checkBox = new CheckBox();
Controls.Add(_checkBox);
base.CreateChildControls();
}
protected override void RenderContents(HtmlTextWriter output)
{
_checkBox.RenderControl(output);
}
}
Registering and placing on the page:
<%@ Register TagPrefix="uc" Namespace="PostBackHandlerApp.Controls" Assembly="PostBackHandlerApp" %>
<uc:SubmitImageControl runat="server" />
Checkbox appears on the page and everything seems fine until we look at the view state. Its value is
/wEPDwULLTExMTg2MzM0NjJkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBR1jdGwwMCRNYWluQ29udGVudCRjdGwwMCRjdGwwMD+PWeqrbtVyQSNMxvfjcmJkKAwpIuEPWJd+m5W6eJtQ
Then, if we simply remove the code Controls.Add(_checkBox);, view state size reduces greatly:
/wEPDwULLTExMTg2MzM0NjJkZLrri0oSGPS9ZiOTsRtSageoskXzCME4KCdRZxOiJyR9
If I move the code of child initialization and adding to OnInit method of my control (where, as far as I know, view state tracing is still disabled), result stays the same. Also, this MSDN article recommends to perform initialization only in CreateChildControls method:
You should create the child controls in the CreateChildControls method and not in OnInit or another life cycle phase. The server control architecture relies on calls to CreateChildControls whenever the Controls collection is needed, such as during data binding (if applicable).
Could anyone explain me why view state becomes larger? Thanks in advance.