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
You can't do that as
ViewStateis page specific and is actually stored in the HTML of the rendered page. You will need to pass the value via aPOSTor 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
ViewStateto transfer data to the same page on Postback.For setting
ViewState:ViewState["FirstName"] = "SuperMan";For retrieving
ViewStateon 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
Sessionvariable 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:
For retrieving
Sessionfrom any page till the session is valid:string sFirstName = Session["FirstName"].ToString();Same way you can use
Cookiesalso, but cookies will be stored on the client.