ViewState doesn't remember value from previous page init

1.2k Views Asked by At

What am I doing wrong here. I can't get ViewState to work:

protected void Page_Init(object sender, EventArgs e)
{
            Method1();
}

private void Method1()
{
    Element.Click += new EventHandler(Button_Click);
}
public void Button_Click(object sender, EventArgs e)
{
    if(ViewState["x"] != null) 
               // use ViewState["x"] from previous Page Init
    //do processing ...

    //in the end, store value for future use
    ViewState["x"] = myLabel.Text;
}

I am reloading the page, so first the Page Init is triggered, where I do changes, before these changes I read from ViewState previous value of a variable, then I do processing, then override that value for subsequent use (in my next Page Init), after which I override it again.

Problem is my ViewState is null , it doesn't store/remember the value I gave it at the previous page init Thank you

2

There are 2 best solutions below

2
On

You can't do that as ViewState is page specific and is actually stored in the HTML of the rendered page. You will need to pass the value via a POST or in the query string or store it in a session or you could cache the value in the asp.net cache which you will be able to access on the other page.

You can use ViewState to transfer data to the same page on Postback.

For setting ViewState:

ViewState["FirstName"] = "SuperMan";

For retrieving ViewState on postback:

string sFirstName = ViewState["FirstName"].ToString();

You can use the Context to Transfer data to the one page to another.

Page1.aspx.cs

this.Context.Items["FirstName"] = "SuperMan";

Page2.aspx.cs

string sFirstName = this.Context.Items["FirstName"].ToString();

You can use the Session variable to preserve the common data which is required almost for every page or across the application for the specific user.

For setting Session:

Session["FirstName"] = "SuperMan";

Applied to your code:

public void Button_Click(object sender, EventArgs e)
{
    if (Session["x"] != null)
    { 
        // do processing

        // in the end, store value for future use
        Session["x"] = myLabel.Text;
    }
}

For retrieving Session from any page till the session is valid:

string sFirstName = Session["FirstName"].ToString();

Same way you can use Cookies also, but cookies will be stored on the client.

1
On

ViewState just remember value on its page and can't pass value to another page , for use another session state , like Session variable , query string etc

simple use session variable like this

public void Button_Click(object sender, EventArgs e)
{
    if(Session["x"] != null) 
               // use Session["x"] from previous Page Init
    //do processing ...

    //in the end, store value for future use
    Session["x"] = myLabel.Text;
}