November 01, 2008

ViewState - Dynamic Controls


The first fact that you should know about dynamic controls is that they should be added to the page at each and every page execution. Never wrap the code that initializes and adds the dynamic control to the page inside a “!IsPostback” condition. The reason is that since the control is dynamic, it is not included in the compiled class generated for the page. So, the control should be added at every page execution for it to be available in the final control tree. The second fact is that dynamic controls play “catch-up” with the page life cycle once they are added. Say, you did the following:

Label lbl = new Label();
Page.Controls.Add(lbl);

Once the control is added to the “Controls” collection, it plays “catch-up” with the page life cycle, and all the events that it missed are fired. This leads to a very important conclusion: you can add dynamic controls at any time during the page life cycle until the “PreRender” event. Even when you add the dynamic control in the “PreRender” event, once the control is added to the “Controls” collection, the “Init”, “LoadViewState”, “LoadPostbackdata”, “Load”, and “SaveViewstate” are fired for this control. This is called “catch-up”. Note though that it is recommended that you add your dynamic controls during the “PreInit” or “Init” events. This is because it is best to add controls to the control tree before tracking of the Viewstate of other controls is enabled…

Finally, what is the best practice for adding dynamic controls regarding Viewstate? Let us say that you want to add a Label at runtime and assign a value to its “Text” property. What is the best practice to do so? If you are thinking the below, then you are mistaken:

Label lbl = new Label();
Page.Controls.Add(lbl);
lbl.Text = "bad idea";

You are mistaken because using the above technique you are actually storing the value of the “Text” property in the Vewstate. Why? Because, recall that once a dynamic control is added to the “Controls” collection, a “catch-up” happens and the tracking for the Viewstate starts. So, setting the value of the “Text” property will cause the value to be stored in the Viewstate.

However, if you do the below, then you are thinking the right way, because you are setting the “Text” property before adding the control to the “Controls” collection. In this case, the value of the “Text” property is added with the control to the control tree and not persisted in Viewstate.

Label lbl = new Label();
lbl.Text = "good idea";
Page.Controls.Add(lbl);

0 comments: