BlueChameleon
BlueChameleon

Reputation: 934

Viewstate and custom controls in asp.net

I have a question about viewstate and custom controls in asp.net.

Say I have a page and a simple composite control on it. I know that in the composite control I have to load all my children control on Page.OnInit so that their viewstate can be applied and be ready for OnLoad.

Now say I have a tree on the page and based on the selected node I would like to load a certain custom control. The treeview's selectedNode is not available during OnInit, but is available on OnLoad and after. I also know that if I add a custom control on the OnLoad of a page that customs control's cycle is still going to start with OnInit and then to OnLoad, etc etc.

So my question is, if the custom's control's OnInit is still being called even though I am loading this control in the parent's OnLoad method, why doesn't the viewstate get populated for the custom control?

Is it because the parent contains the the viewstate for the children and if i load children from parent's OnLoad the viewstate is not available?

How do you usually go about loading custom controls if you have a situation I described above (with the treeview)?

Upvotes: 4

Views: 1780

Answers (1)

Michael Liu
Michael Liu

Reputation: 55359

ASP.NET does load viewstate for child controls even if they're added to the page in OnLoad, as this example demonstrates:

protected override void OnLoad(EventArgs e)
{
    Literal literal = new Literal();
    this.placeHolder.Controls.Add(literal);
    if (!this.IsPostBack)
        literal.Text = "I'm still here after a postback.";
}

Note that, by default, ASP.NET loads viewstate based on the indexes of the child controls, so make sure the order of your controls is consistent from one postback to the next.

Upvotes: 1

Related Questions