Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewstate variable lost on user control loaded dynamically

I have a problem with ViewState. I have an aspx page that has a treeview on the left and an UpdatePanel with an ASP.NET Panel inside on the right. It is in that inner Panel where I load and unload dynamically user controls. I use that update panel to load dynamically controls.

I also made a custom control for my user controls because I need to pass some values from page. On that constructor I use ViewState to store these values.

The first time I load the user control I call its constructor with parameters. When I reload that user control on each postback I use its normal constructor.

My problem is I the values I've stored on ViewState has become null on successive postback.

Update:

This is a piece of my user control:

public class MyUserControl : System.Web.UI.UserControl
{
private int PKId
{
    get { return ViewState["pkId"] as int; }
    set { ViewState["pkId"] = value; }
}

public MyUserControl(int pkId)
{
    this.PKId = pkId;
}

...
}

I'm following this article to load controls dynamically: http://msdn.microsoft.com/en-us/magazine/cc748662.aspx#id0070065.

Second Update:
I also set the same control ID when I load the user control at first time and on each reaload.

Maybe I can use another method to store these values like input hidden fields or Cache. I've choosen ViewState because I don't want to overload server with Session values for each user.

Third update:

I load the controls with this code:

System.Web.UI.UserControl baseControl = LoadControl(ucUrl) as System.Web.UI.UserControl;
if (baseControl != null)
{
    baseControl.ID = "DestinationUserControl";
    PanelDestination.Controls.Add(baseControl);
}

And reaload with this code:

DynamicControls.CreateDestination ud = this.LoadControl(TrackedUserControl) as DynamicControls.CreateDestination;
if (ud != null)
{
    ud.ID = "DestinationUserControl";
    PanelDestination.Controls.Add(ud);
}

What's happening?

like image 983
VansFannel Avatar asked Feb 12 '10 15:02

VansFannel


2 Answers

Try storing the control into a local variable once it's loaded/constructed before it's added to the control hierarchy. That allows the ViewState data to be mapped from and to the control. See "Rule 2" here http://chiragrdarji.wordpress.com/2009/05/20/maintain-viewstate-for-dynamic-controls-across-the-postback/.

like image 111
G-Wiz Avatar answered Oct 31 '22 11:10

G-Wiz


When are you loading the user control? This has to happen in the Init event if you want ViewState to be saved/restored.

like image 3
Bryan Avatar answered Oct 31 '22 11:10

Bryan