Problems with ViewState: "function 'ViewState.get_Item' evaluated and returned null"

S

Steph

I am trying to save a simple integer value in ViewState. I set the
value in the Page_Load() event and retrieve it in the function
Page_Unload() event. The value seems to be set correctly, but upon
the next Page_Load(), I get the following error when I try to retrieve
the value from ViewState:

"function 'ViewState.get_Item' evaluated and returned null".

The page does have a form on it with the runat="server" attribute set.
From the MSDN documentation, this seems to be all you have to do.

What am I doing wrong?

I have created a simple test page that illustrates the problem. Here
is the code behind the page:

public class Testing : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected int modPageMode;
private void Page_Load(object sender, System.EventArgs e)
{
Page.EnableViewState = true;

// Initial page load
if (!Page.IsPostBack)
{
modPageMode = 1;
}
// Post back
else
{
// Set the page mode
modPageMode = (int)ViewState["PageMode"];
}
}
private void Page_Unload(object sender, System.EventArgs e)
{
ViewState["PageMode"] = modPageMode.ToString();
}

private void Button1_Click(object sender, System.EventArgs e)
{
modPageMode = 2;
}
}
 
B

bruce barker

updating viewstate in Unload is not very useful. the page has been rendered,
so the client will not see the update, nor send it back.

PreRender is your last chance to update Viewstate.

-- bruce (sqlwork.com)
 
Joined
May 11, 2011
Messages
1
Reaction score
0
Answer

Save the ViewState in an earlier event.

Then in Page_Unload, call

this.SaveViewState()

That will update the values while in the page_unload event.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top