Search code examples
asp.netdynamiccontrolslifecycle

Why can ASP.NET Dynamic controls keep the ViewState even when added in Page_Load?


I have done a bit of research related to dynamic controls and ViewState.

And I read that in order to keep the ViewState for a dynamic control you have to add it in the Page_Init event. It makes sense because the PageLifeCycle is :

  1. Initialization.
  2. LoadViewState.
  3. LoadPostbackData.
  4. Load.
  5. RaisePostbackEvent.
  6. SaveViewState.
  7. Render.

But I made a test app and I saw that the ViewState and properties values are preserved even if I add the control in the Page_Load event and not after. From this on I only found contradictory informaton. Some say that the controls may catch up the PageLifeCycle other say you must add them in the Page_Init. Can someone clarify this for me?

Also in msdn I found:

Note You may be able to get away with loading your controls in the Page_Load event handler and maintaining the view state properly. It all depends on whether or not you are setting any properties of the dynamically loaded controls programmatically and, if so, when you're doing it relative to the Controls.Add(dynamicControl) line. A thorough discussion of this is a bit beyond the scope of this article, but the reason it may work is because the Controls property's Add() method recursively loads the parent's view state into its children, even though the load view state stage has passed.

But I don't really understand this fully so I hope someone can explain it. Thank you in advance.


Solution

  • This code will demonstrate it in action:

    protected void Page_Load(object sender, EventArgs e)
    {
        Button b1 = new Button();
        Button b2 = new Button();
        if (!IsPostBack)
        {
            b1.Text = "Button1";
        }
        this.form1.Controls.Add(b1);
        this.form1.Controls.Add(b2);
        if (!IsPostBack)
        {
            b2.Text = "Button2";
        }
    }
    

    so if you modify the control after it is added to the form it keeps its viewstate, but if you modify it before you add it to the form the text doesn't make it into the viewstate. This is what happens - exactly why it is like that is another questions (it is actually the reverse of what I would have thought reading the docs).

    EDIT
    I forgot to mention - essentially this is due to the fact that the control plays through the page lifecycle to "catch up" with the page when it is added to the control tree through Controls.Add() - there are endless articles on this because there isn't a lot about it that is straightforward.