Using ViewState in c# code


I want to access a variable through out my project.So,i am using a viewstate .
I am assigning value  for a viewstate variable  in this way
viewstate["username"]="xxx" in one page ,
i am not able to acess it it another page in the same project.
Is there anything i need to do to access it through out the project.
Who is Participating?
greigtechConnect With a Mentor Commented:
There are many ways you can access variables throughout the application:

Session will live for the life of the users session:
Set it:
HttpContext.Current.Session.Add("VarName", "varValue");
Access it:
String x = (string)Session["VarName"];

** Or you can Cache it** which is great if you want to set dependencies and expiration.
HttpContext.Current.Cache.Add("VarName", "VarValue", null,null,null,null,null);
Access it by:
 String x = (string)Context.Cache["VarName"];

**or if you just want it alive during the duration of the call:
HttpContext.current.Items.Add("VarName", VarValue);
Access it by:
string s = (string)HttpContext.Current.Items["VarName"]

Hope it helps!

You can cache it

Viewstates are accesiable only on the page that u have declared It, Viewstates cannot be accessed across pages.Use Sessions to achieve u r functionality
//First Page

//Second Page
string strtest=Sessions["username"].ToString();
//it is not Sessions

//First Page

//Second Page
string strtest=Session["username"].ToString();
lakshmidurgaAuthor Commented:
I have tried session.But,i am facing problems with session variables,when deployed in IIS.I am getting object reference not set to an object error at the statement
if i comment out that statement it is functioning well.

This statement even working fine when i run my application using visual studio 2005.
Please help me in any other necessary code i need to code when using sessions in c#.
I have used session variables many times with code.They went well.This is the first time i am writing c# code.
please post u r code
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.