Why are my Dynamic Controls not persisting via ViewState

Currently I am having the issue that when I create dynamic controls, even though I re-create them they still lose their respective ViewState. How can I ensure that my Dynamic ASP.Net controls and User Web Controls save their ViewState?

When a dynamic control is added to another control, the recently added dynatic control plays catch-up to get to the stage that the parent control is in (see attached picture at the bottom. Obtained from the MSDN website).  This is important beceause at one point controls begin tracking their viewstate. The main issue at hand is that values added before the control is tracking viewstate won’t make it to viewstate and will be lost on PostBack.

So what works and what doesn’t? If you already loaded your page the form is already tracking view state so if you add the dynamic control to the control collection before you set the values (by binding or setting the properties directly) then your changes will be tracked by the ViewState. You will find it doesn’t work however, if you set the values of the dynamic controls before you add them to the form’s controls collection. Here are some examples:

Incorrect method:

 

TextBox myTextBox = new TextBox();

if(!IsPostBack)

{

//  This value wil not persist as it is being set before the Textbox is

// added to the ControlCollection

myTextBox.Text = “Value that I want to persist via ViewState”;

}

this.Controls.Add(myTextBox);

Correct method:

TextBox myTextBox = new TextBox();

//  TextBox is added to the ControlCollection. It will catch up to the state

// where it can maintain a ViewState

this.Controls.Add(myTextBox);

if(!IsPostBack)

{

//  This value wil persist

myTextBox.Text = “Value that I want to persist via ViewState”;

}

Important Additional Note:

By adding a control BEFORE you set its properties, you allow for it to participate not only in ViewState but in the rest of the page lifecycle as partially shown above through the diagram.

Additional Resources:

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.