This documentation is archived and is not being maintained.

Code: Reading Values From Session State (Visual C#)

Visual Studio .NET 2003

This example accesses the HttpSessionState.Item property to retrieve the values in session state.


string firstName = (string)(Session["First"]);
string lastName = (string)(Session["Last"]);
string city = (string)(Session["City"]);

Compiling the Code

Start a new ASP.NET application and paste the code into the Page_Load method.

Robust Programming

Session values are of type Object. You should cast to the appropriate type when reading them.

No exception is thrown if you attempt to get a value out of session state that does not exist. To be sure that the value you want is in session state, check first for the existence of the object with a test such as the following:

if (Session["City"] == null) 
    Response.Write("No such value in session state.");

If you attempt to use a non-existent session state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown.

See Also

Code: Reading a Value From View State (Visual C#) | Introduction to Web Forms State Management | Saving Web Forms Page Values Using View State | State Management Recommendations | ASP.NET State Management | Web Applications Example Topics