Geeks With Blogs
BizTalk Blog by Chris Han System Design for Enterprise Agility,

I was trying to create and page with Asp.NET 2.0 and Ajax 1.0.

I was using a placeholder control to dynamically load a user control based on the user selection.

The first error I encountered is :

{"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, when adding controls dynamically, the

controls added during a post-back must match the type and position of the controls added during the initial

request."}

This is because I'm suppose to load the same user control on every page request, not only in (!IsPostBack) block. I solved that by moving the loading code to Page's OnInit event handler. According to MSDN article, http://msdn2.microsoft.com/en-us/library/ms972976.aspx#viewstate_topic4, here is the time when the page can load all of it's child controls before restore their viewstates.

After that, everything looks fine except that I can't get the value I entered into the dynamically loaded user control when post back! To make it more interesting, when keep the same user control loaded (don't load other user controls), I enter the value again, and click submit again, boom! You got it.

What could be wrong? After a day of scratching head and debugging, I notice that every time I load a different control, the loaded user control's ID is randomly assigned such as 'ctl26'. So I explicitly specify the ID before load it:

Control ctl = LoadControl(ControlPath);

ctl.ID = "UcSecuritySubTypeDetails";

placeHolderSecuritySubTypeDetails.Controls.Add(ctl);

Now everything works together. So the keys of using dynamically loaded control is:

1. Load it every time.

2. Give it an explicit ID

One thing I need to clarify is that initially I was loading the dynamic control in Page_PreInit event handler as suggested by the MSDN article: http://msdn2.microsoft.com/en-us/library/ms178472(VS.80).aspx. It says PreInit event is typically used for "Create or re-create dynamic controls". But if do as such, I will get an error complaining that the object of my placeholder control is not yet instantiated.  That is because although Page is derived from Control class, but at Page_PreInit stage of the Asp.NET life cycle, only Page object is created, all sub-controls include the placeholder are initiated after Page_PreInit and before Page_Init. Check Alex Arkhipov's nice post here for details of Asp.NET 2.0 Page life cycle:
http://blogs.vertigosoftware.com/alexark/archive/2005/05/06/898.aspx

Page_Init is the best place you can load the dynamic controls into a parent control other than the Page.

Posted on Tuesday, March 27, 2007 10:01 AM Asp.Net 2.0 | Back to top


Comments on this post: Dynamically Loaded Control can not maintain values at PostBack?

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
There's also a ctl.ClientID property which will give you the run-time ID of the control at design time...

//Code-Behind
Control ctl = LoadControl(ControlPath);
ctl.ID = "UcSecuritySubTypeDetails";
placeHolderSecuritySubTypeDetails.Controls.Add(ctl);

String js = "alert(document.getElementById('" + ctl.ClientID + "').value);";

I know nothing about c# so I hope that's the syntax, but I've done very similar things in VB.



Left by kyle on Mar 27, 2007 1:04 PM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
i am trying to do something similar. i want to load my control based on value selected in another user control. so i will know only after event like mouseclick event in another control what type of control do i need to load. so does that mean ican't load my control dynamically? because mouse click event will occur only after those pageload and init event.
Left by gkeeara on Apr 19, 2007 3:37 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
hi...

i m building a digital library for folders and files...

in this i add imagebuttons and checkboxes into a gridview at runtime...

when i check any of checkbox on postback all controls disappear...

i want to catch whether checkbox is checked or not before postback...

plz help...
Left by Ritesh Nagpal on May 02, 2007 7:33 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Denis Bauer has created a Dynamic Placeholder that maintains the viewstate of dynamically loaded controls. He also provides the source. Without this code this module simply would not work.

http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
Left by Michael Washington on May 12, 2007 9:33 PM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Thanks Michael! Gonna check it out.
Left by Chris Han on May 13, 2007 12:20 PM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
I have a similar problem but instead of aContentPlacHolder I'm trying to add the web user controls to a UpdatePanel. Find a description of my problem here:

http://forums.asp.net/p/1085154/1726388.aspx

I will appreciate any help, thanks
Left by Reynaldo on May 26, 2007 12:32 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Perhaps this will be helpful.
http://weblogs.asp.net/infinitiesloop/archive/2008/04/23/truly-understanding-dynamic-controls-by-example.aspx
Left by Dave Reed on Apr 23, 2008 6:33 PM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
i am also doing the same sort of work but in my case i am having a grid display some information and on every row chas a blink button on clicking it modal popup extender will opne by loading the control dynamiclally in a panel ant then the control will be shown in modal popup all is doing fine here but the problem i am having here is this in user control i have a list box an d i want hsi list box to be filled on first show of modal popup but the controlis not firing the event of ! Is postback and if i palced hte code at some where else i am unable to ge the selected values coz on every post back
Left by Sahar on May 20, 2008 3:19 PM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Thanks after searching for two days this really did the trick Yehhhaaaaa and happy coding to all the other coders out there :)
Left by Dextor Boy Genius on Oct 01, 2008 8:35 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
WHAT"S THE POINT OF A DYNAMIC PLACEHOLDER METHOD (THAT YOU HAVE TO HARD CODE THE NAME AND URL OF ANOTHER CONTROL...? THAT YOU HAVE TO LOAD INSIDE OF A PAGEInit..? It's not really Dynamic anymore at this point because your saying you need to know of it before it's existence.


What about something like this:

you have a "~/CONTROLS/mycontrol.ascx"

you have a "App_Code/MyDynamicControlClass.cs"

MyDynamicControlClass.cs looks like this:
////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// Summary description for Class1
/// </summary>
public class DynaChart : System.Web.UI.UserControl
{
public DynaChart(String[] tempstring, Int32[] tempint)
{
BaseCHART ucDynamic = (BaseCHART)LoadControl("CONTROLS/mycontrol.ascx");
Controls.Add(ucDynamic);

}
}
////////////////////////////////////////////////////////////


Inside the Default.aspc.cs page: I now have the liberty to do:

////////////////////////////////////////////////////////////

protected void Button2_Click(object sender, EventArgs e)
{

DynaChart CHART1 = new DynaChart(sItems, iValue);
Panel1.Controls.Add(CHART1);

}

////////////////////////////////////////////////////////////

OK SO NOW THAT WE"VE CREATED A CONTROL OUT OF THIN AIR, NOW LET"S - FIGURE OUT A WAY TO STORE (CHART1) FOR POSTBACK.
Left by Damon Sanchez on Nov 18, 2008 11:07 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
thank you million timessssssssssssssssssssssssss
Left by ahmed on May 02, 2009 8:13 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Thanks

Read in conjunction with:
http://msdn.microsoft.com/en-us/library/ms972976.aspx

saved me tonnes of time.
Left by Yashin on Oct 28, 2009 2:32 PM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Thanks that worked for me :)
Left by Matthew on Aug 24, 2010 2:32 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Thanks!!! I spent 2 days looking for solution before I found your post.
Left by Go Ro on Dec 29, 2010 2:49 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Glad it helps. Happy new year.
Left by Chris on Dec 29, 2010 8:54 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
This is the great post. Really helped me.
many thanks.
Left by ls on Jun 21, 2011 9:59 PM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
You are one talented coder, I have to give you that. I had the same problem and didn't manage to find the glitch in the system. Thanks for the tutorial here. Now I know exactly what to do.
Left by cloud computing security on Jun 22, 2011 7:50 AM

# re: Dynamically Loaded Control can not maintain values at PostBack?
Requesting Gravatar...
Thanks, it very usefully for me. ^^
//////////////////////////////////////////////////////////
Denis Bauer has created a Dynamic Placeholder that maintains the viewstate of dynamically loaded controls. He also provides the source. Without this code this module simply would not work.

http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
Left by Kenji on Oct 26, 2012 9:18 PM

Your comment:
 (will show your gravatar)
 


Copyright © Chris Han | Powered by: GeeksWithBlogs.net | Join free