Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A problem to load user controls dynamically?!

Status
Not open for further replies.

Plato2

Programmer
Dec 6, 2002
192
US
I'm trying to load user controls dynamically.
When I load a user control first time it works fine but when I load another cotrol to replace my current control it gives an error.
Here is my main page:

private void Page_Load(object sender, System.EventArgs e){
control_id=ViewState["selected_category"].ToString();
if(control_id=="phones"){
plhMain.Controls.Clear();
Control control = LoadControl ("ucPhones.ascx");
plhMain.Controls.Add(control);}
else if(control_id=="main"){
plhMain.Controls.Clear();
Control control = LoadControl ("ucMain.ascx");
plhMain.Controls.Add(control);}
}

When I load User Control second time I receive the following 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, 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.

How Can I solve this problem?
Thanks in advance!
 
Bump...

I am having the same issue, except mine happens on postback and I'm loading the same .ascx control!

Code:
theMainPane.Controls.Clear();
theMainPane.Controls.Add(LoadControl("whatever.ascx");

I have a LinkButton on the "whatever.ascx" page that does a postback, but has no code in the click event (I made it empty just to see if it would work). When I click on the LinkButton, it procedes to postback. LoadControl works fine, but adding it to theMainPane give the excact same error as the previous post mentioned.

I stepped through the code and I am loading this control the same every time and in the same order. Any ideas?

Best regards,
Akusei
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top