Failed To load viewstate when loading usercontrols

J

j-in-uk

I have linkButtons on my page, onclick of the link button I want to
load the proper usercontrol, this works fine the 1st time I click but
when I click the 2nd linkButton

I get "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 all the code I have on my page. Any help pls.Thanks


protected void LButton1_Click(object sender, EventArgs e)
{
plcH.Controls.Add(LoadControl("Control1.ascx"));
}



protected void LButton2_Click(object sender, EventArgs e)

{
plcH.Controls.Add(LoadControl("Control2.ascx"));
}

I'm assuming I need to reload the controls in Page_Init()
Do I check again which button is clicked inorder to reload the
controls?
 
M

Muhammad Naveed Yaseen

1) It is usually better to stay away from dynamic addition/removal of
control in ASP.NET for several reasons. If possible, try to achieve
same purpose by making controls visible/invisible.

2) If one has to add/remove dynamically, then one must ensure that
control tree (i.e. types and positions of controls) at each Init is
same as it was in last PreRender.

In your case, you are probably just adding controls once in the event
handler (which is not a good place to add/remove controls anyway) but
not adding it in next postbacks.

Regardless of which button was clicked or not clicked, regardless of
even if you need that control anymore or not, you have to add it next
postback if you want to use viewstate on page (otherwise you can
disable viewstate and forget about making control tree same).

3) When dynamically loading User Controls (i.e. ascx), it is usually
better to call LoadControl through TemplateControl property of inner-
most control in hierarchy. In your case it would be
plcH.TemplateControl.LoadControl()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,698
Latest member
LydiaHalle

Latest Threads

Top