Adding controls dynamically to a page in ASP.NET
posted on Friday, September 30, 2005 by bobby @ 1:13 pm
ASP.NET added viewstate in an attempt to persist state for controls across postbacks. Viewstate does what it's supposed to, but also presents some challenges when adding controls dynamically. If you've ever tried to modify the control hierarchy before viewstate has fully loaded, you've prolly seen this error:

"Failed to load viewstate.
The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.
"

For example, if I dynamically add a textbox to a page, that textbox MUST exist before the viewstate for the page is loaded after a postback. This is because the when the page attempts to load viewstate, the control hierarchy must match the control hierarchy that existed when viewstate was originally created.

So when you add a control dynamically, it must exist during the postback - at least long enough for viewstate to be loaded properly. This usually involves re-adding any dynamic controls that were present at last page load. What this means is that you can dynamically add, update and remove controls, but only at certain times in the page's lifecycle. Here is a breakdown of a typical page lifecycle:

Note: I'm omitting events and methods invoked by IPostBackDataHandler and IPostBackEventHandler for the purpose of this article.

  • Instantiate - by constructor.
  • Initialize - This is when the markup code is initialized into the control hierarchy. The Init event is fired and OnInit is called.
  • Load Viewstate - The LoadViewState method is called.
  • Load - The Load event is fired and the OnLoad method is called.
  • Pre Render - The PreRender event is fired and the OnPreRender method is called.
  • Save Viewstate - The SaveViewState method is called
  • Render - The Render method is called.
  • Unload - The Unload event is fired and the OnUnload method is called.



Given the above series of events, dynamically added controls should be added before the LoadViewState method is called and they must be added in the exact same order they were added on the previous page load. If they are out of order, or a control is missing, you'll get that stellar exception above.

So, when do you do it? Well, to me, Initialization seems to be the best place. Add the controls back in during the OnInit method. Let viewstate completely load itself back up, then do whatever you want... add more controls, remove existing controls, etc. Just make sure you add/remove controls before SaveViewState is called - this shouldn't be a problem to most since the only way to eff this up would be during the Render method - and if you're messing with the control hierarchy here, then you prolly shouldn't be reading this article.

Knowing the page's lifecycle of events and the timing of critical methods is paramount to getting dynamic controls to work. If you don't learn it well, you'll spend ten fold the amount of time fixing related bugs - and to me, these are the most frustrating to debug.

CommentsComments
posted on Wednesday, March 15, 2006  by Chris Katsuo @ 9:46 PM

Hi,

You should look at the Page.LoadControl method in .NET 2.0.

You can add the control in the onLoad event, because the dynamically added control will go through the LoadViewstate events even if the LoadViewState event is alreday finished for the page.

Regards
posted on Tuesday, April 04, 2006  by Igor Kikena @ 2:36 AM

There is one important issue that is not addressed in your article and is a cause for the same error. When controls dynamically added as result of a postback event, the container (page, placeholder etc) will invoke recursive method for each new control (Control.LoadViewStateRecursive) to load viewstate for newly added controls. Unfortunately, those controls did not exist when page persisted viewstate and page will crash.
posted on Thursday, April 06, 2006  by Chris Katsuo @ 3:24 AM

Hi

The comment of Igor is about .NET 1.1.

You can add controls in a postback event without any problem with the LoadControl in .Net 2.0.

Regards
posted on Sunday, April 09, 2006  by ALBERT @ 10:51 PM

First of all, thank you for the article. I have a page that loads dynamically a series of user controls, always in the same order and from the onInit event. All these user controls are the same except one, which loads a different *.ascx file depending on the postback. From the five choices available to the user (five different *.ascx files) there is ONE , only ONE, that provokes this error. And this error has appeared after adding a new control (a datagrid) to that *.ascx file. If I delete the datagrid, the page works well. Any suggestion? Thanks in advance
posted on Sunday, May 28, 2006  by Anonymous @ 11:41 AM

The datagrid has the EnableViewState property set to true by default, the others are probably controls like a literal or label which have a default value of false. All of the problems mentioned above are irrelevant if you do not need the ViewState for the control being added, which is true for most dynamically added controls.
posted on Wednesday, September 13, 2006  by Anonymous @ 3:15 AM

I little precisation, a "parent" control can also add dynamic children controls in the LoadViewState. This is useful when you save some information of the children controls in the viewstate.

For example, if your "parent" control has x DropDownList in his children controls, and you save the x in the viewstate, you can use the following code:

Copy code to clipboard in IE or select code for Firefox
protected override void LoadViewState(object savedState)
{
  base.LoadViewState(savedState);
  for (int num1=0;num1<this.NumberDropDownList;num1++) this.Controls.Add(new DropDownList());
}


That because the ViewState of the children controls is loaded only after leaving the parent LoadViewState method]
posted on Thursday, February 15, 2007  by C @ 1:02 AM

So what is the solution to having a DataGrid (with ViewState enabled) in a dynamically added UserControl? I have a page with about 20 UserControls that I want to load individually from a TreeView vontrol (a roundabout way to replace the use of frames)

I have a hidden textbox that then keeps track of what UserControl is currently loaded.

OnLoad of the parent page I say:


if (currentControl.Text != "")
{
UserControl uc = (UserControl)Page.LoadControl(currentControl.Text);
PlaceHolder1.Controls.Add(uc);
}


Then for my TreeView selectedNodeChanged


protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
TreeView t = (TreeView)sender;
UserControl uc = (UserControl)Page.LoadControl(t.SelectedValue);
for (int i = 0;i< PlaceHolder1.Controls.Count;i++ )
{
PlaceHolder1.Controls.RemoveAt(i);

}

PlaceHolder1.Controls.Add(uc);
currentControl.Text = t.SelectedValue;
}



But I get the following error

The SqlDataSource control 'DSPartyList' does not have a naming container. Ensure that the control is added to the page before calling DataBind.

Where DSPartyList is a DataGrid on the previously loaded control.

Any assistance would be great!

C.
posted on Friday, March 02, 2007  by Anonymous @ 7:50 AM

Good article, for a better understanding of page life cycle and the events n methods called during the page ...
posted on Friday, April 20, 2007  by Artem @ 3:28 AM

As I know you can add controls without any problems till (including) the OnLoad phase. Even though LoadPostbackData event gets called before this phase, controls, that were added on OnLoad phase, are participating in LoadPostbackData event and are able to load their view state as page scrolls all phases for such controls till OnLoad phase.
This applies both for .Net 1.1 and .Net 2.0
posted on Thursday, April 03, 2008  by Anonymous @ 10:03 PM

hahahahah
posted on Friday, April 18, 2008  by Louis @ 1:33 PM

I recognize myself in this part of the article

"nd if you're messing with the control hierarchy here, then you prolly shouldn't be reading this article."

That's me !!!!

Ok then I'll continue to search why my code is still giving me the ViewState error.

By the Way, thanks for the article

Louis
posted on Monday, April 21, 2008  by Anonymous @ 1:31 AM

hi hi hi
posted on Monday, July 14, 2008  by Chris Hunt @ 6:07 AM

Chris Katsuo thank you! your LoadControl comment just saved my life (or maybe just my job :))
posted on Tuesday, July 29, 2008  by Shant Hagopian @ 9:13 AM

Sweet article!

Now I have a dynamically created user control that has dynamically created checkboxes in it :)
posted on Friday, May 08, 2009  by Anonymous @ 4:21 AM

ytutyyu
posted on Monday, May 18, 2009  by Instant Host @ 12:07 AM

Hi,
I love to work in ASP.Net.
Thanks for the info and thanks for the sharing your link
posted on Tuesday, May 19, 2009  by Anonymous @ 7:44 AM

I HATE to work in ASP.Net. I absolutely loathe it. Tasks that are so simple in classic ASP are way too complex in .NET.

Maybe it's time to change careers again.
posted on Wednesday, June 24, 2009  by How to play craps in a casino online @ 12:43 AM

I think it's a Incomplete article. i appreciate senthil for writing an article and publish in asp.net website. If you add button we should need to handle it Click event at least. We need to preserve the dynamic controls if the page post back. We can't say this an article, but a small tip for how to create asp.net controls at run time.
posted on Tuesday, June 30, 2009  by ZK@Web Marketing Blog @ 3:44 AM

ASP.NET has gone in unmanaged and unstable state where we have 100s of project coded in ASP.NET 2.0 and when we open them in 2008 nothing opens, upgrading to 3.5 are mere nightmares. And finally so many new technologies just to boost the marketing headlines. But come on guys, its easy for one blogger to just blog about able to mix technologies with writing 100s of lines of code which one geek can understand. Have you even worked on any project involving more then 5 developers? Practically we are spending more monty to train new things to our staff, more money to buy new tools, more money to manage projects and more and more money to sit and search world of forums to find why one thing doesnt work then actually doing simple development.
posted on Wednesday, July 08, 2009  by Anonymous @ 7:29 AM

I've yet to have a client request a simple application.... Hard to do SIMPLE development if none of the applications we are asked to write are simple in nature. I'm guessing if you have unstable asp.net code then someone was using an approach that wasn't well structured. Most likely they either didn't know enough to accomplish a good structure OR they weren't given the time to develope a good stable structure (usually the case). General rule of thumb is the more rushed the development the sooner you get to throw it away and do it again.
posted on Friday, October 30, 2009  by sexy corsets        @ 3:50 AM

First, import the "System.Data.OleDb" namespace. We need this namespace to work with Microsoft Access and other OLE DB database providers. We will create the connection to the database in the Page_Load subroutine. We create a dbconn variable as a new OleDbConnection class with a connection string which identifies the OLE DB provider and the location of the database. Then we open the database connection:
posted on Thursday, January 07, 2010  by Anonymous @ 3:49 PM

Nice!
posted on Friday, January 29, 2010  by ppo insurance plans @ 9:32 AM

How does visual studio run in Parallels? I've got a macbook pro, and develop / work on .net applications (so i need windows) at the moment im using bootcamp. But im in love with Mac OSX, and would love to use it for things like email, documents, msn messenger and the web. But then need to be able to use Windows for Visual Studio 2005! In parallels does intellisense work? How do things compile (fast enough) ? Ever used Mono?
posted on Thursday, February 04, 2010  by flash development  @ 5:10 AM

I have never been impressed by posts developed on the web but this one makes me change my mind.
posted on Thursday, February 18, 2010  by campioni di Blackjack online @ 2:33 AM

Can someone explain how to get jQuery validation working with this release? It seems like lots has changed/moved since previous releases - making it very hard to get a straight answer from Google!
posted on Monday, February 22, 2010  by white dresses @ 1:37 PM

Thank you very much for the information. I think it will add a great effect to my article, I am almost sure. Anyway the feedback is truly positive! wish you good luck in your work and will be waiting for novelties!


New Post Notification

Search Posts

Recent Posts


About Meeself
People call me Bobby DeRosa
I live somewhere in San Diego, CA
MCSD, MCAD, MCP

This theme was adapted from fUnique by fahlstad        Icons by FamFamFam        XHTML 1.0 Strict; tuned for Mozilla-powered browsers

Admin Login Administrator Login
Invalid login attempts are logged.
  Username:
  Password: