Click here to Skip to main content
14,874,323 members
Articles / Web Development / XHTML
Posted 31 Jan 2009


11 bookmarked

How to Utilize Session Variables

Rate me:
Please Sign up or sign in to vote.
2.82/5 (5 votes)
31 Jan 2009CPOL3 min read
An article on how to utilize session variables


This article basically discusses how to utilize session variables. Sometimes, developers forget to remember the name of Session variables. For example, in the general scenario when a user logs into the web application system, as a developer, we store UserID to the session.

Now, the problem arises when it is required to store more than one variable into the session like UserID, UserType, UserRole, UserCurrentBalance, etc. At that time, the developer stores this information into the session as per her/his naming style.

For example:

Session["_UserID"] = // Database information

Now, if we need to use this UserID information from the session at runtime, we generally write like this:

int UserID = (int)Session["_UserID"].ToString();    

Here, in this case, we manually have to cast our Session variable value to String.

So, If our session variable has information of different types like FullName and CurrentBalance, we have to manually cast our session variable values to appropriate types when we're going to use it.

What We Can Do

To solve this problem, I've introduced a class named SessionManagement. This class will have properties as per your requirement of Session variables.

Let's see how can we do this to utilize Session variables.

Using the Code

Our first step is to create the SessionManagement class.

Add a new class in your solution explorer named SessionManagement.cs and create different properties as per your demand of Session variables.

public class SessionManagement
       public int UserID
           get { return HttpContext.Current.Session["UserID"] == null ? 0 :
               (int)HttpContext.Current.Session["UserID"]; }
           set { HttpContext.Current.Session["UserID"] = value; }
       public string UserType
           get { return HttpContext.Current.Session["UserType"] == null ?
       string.Empty : HttpContext.Current.Session["UserType"].ToString(); }
           set { HttpContext.Current.Session["UserType"] = value; }
       public decimal UserCurrentBalance
           get { return HttpContext.Current.Session["UserCurrentBalance"] == null ?
       0 : (decimal)HttpContext.Current.Session["UserCurrentBalance"]; }
           set { HttpContext.Current.Session["UserCurrentBalance"] = value; }

Here, in the above SessionManagement.cs class, I've created three properties of three different type values UserID as int, UserType as string and UserCurrentBalance as decimal, because I want to store user's UserID, UserType and UserCurrentBalance into session when the user logs in.

Our second step is to create a BasePage that inherit System.Web.UI.Page class, so that we can directly use our Page session into the code and by doing so, we can also directly use our properties of the SessionManagement class.

Add another new class in your solution explorer named BasePage.cs, inherit System.Web.UI.Page class in it and create only one property in the same way as given below:  

public class BasePage : System.Web.UI.Page
       private SessionManagement _SessionManagement;
       public SessionManagement SessionManagement
               if (Session["SessionManagement"] == null)
                   _SessionManagement = new SessionManagement();
                   Session["SessionManagement"] = _SessionManagement;
                   _SessionManagement = Session["SessionManagement"] as
               return _SessionManagement;

After creating the BasePage class, it's time to use it.

Add a new WebForm in your solution explorer named Default.aspx and go to the codebehind part of this page. 

You will see the following after adding a new Default.aspx page's code behind in your solution explorer.

public partial class _Default : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)

Remove the inherited class 'System.Web.UI.Page' from your page code behind class.

Inherit our BasePage class in _Default page class like this:

public partial class _Default : BasePage
        protected void Page_Load(object sender, EventArgs e)

After this, you can directly assign your database information values of the user into the session and you can also directly use it.

Here is the example of storing user information into the session by this mechanism when a user logs in successfully.

I'm giving you a simple example of user login and storing information to the session by our SessionManagement class if the user login credentials match.

protected void btnLogin_Click(object sender, EventArgs e)
          // This is suppose your UserInformation class to validate
     // that user credential is valid or not.
           UserInformation objUserInformation = new UserInformation();

           objUserInformation.UserID = txtUserID.Text;
           objUserInformation.Password = txtPassword.Text;

           // If UserID and Password match, we'll store user information
      // to the session by SessionManagemenbt class.
           if (objUserInformation.IsUserAuthenticated())
               // This is the actual use of storing values to the session
          // by SessionManagement class
               this.SessionManagement.UserID = (int)objUserInformation.UserID
               this.SessionManagement.UserType = objUserInformation.UserType.ToString();
               this.SessionManagement.UserCurrentBalance =
               lblMessage.Text = "Invalid UserName or Password.

Similarly, you can retrieve session information directly to any page of your project, but remember one thing that the page must be inherited from BasePage instead of from System.Web.UI.Page.

You can retrieve a Session variable like this:

int UserID =  this.SessionManagement.UserID;
string UserType = this.SessionManagement.UserType;
decimal UserCurrentBalance = this.SessionManagement.UserCurrentBalance;

That's it. Hope you like it.


  • 31st January, 2009: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

-- Abhi --
Team Leader
India India
No Biography provided

Comments and Discussions

GeneralMy vote of 1 Pin
Orvindo31-Jan-09 22:18
MemberOrvindo31-Jan-09 22:18 
GeneralRe: My vote of 1 Pin
Colin Angus Mackay1-Feb-09 1:10
MemberColin Angus Mackay1-Feb-09 1:10 
GeneralMinor change means the base page is not necessary Pin
Colin Angus Mackay31-Jan-09 9:51
MemberColin Angus Mackay31-Jan-09 9:51 
GeneralRe: Minor change means the base page is not necessary Pin
nato2331-Jan-09 18:51
Membernato2331-Jan-09 18:51 
GeneralRe: Minor change means the base page is not necessary Pin
-- Abhi --31-Jan-09 20:44
Member-- Abhi --31-Jan-09 20:44 
GeneralRe: Minor change means the base page is not necessary Pin
-- Abhi --31-Jan-09 20:45
Member-- Abhi --31-Jan-09 20:45 
GeneralRe: Minor change means the base page is not necessary Pin
Colin Angus Mackay1-Feb-09 1:07
MemberColin Angus Mackay1-Feb-09 1:07 
GeneralRe: Minor change means the base page is not necessary Pin
-- Abhi --2-Feb-09 2:51
Member-- Abhi --2-Feb-09 2:51 
GeneralRe: Minor change means the base page is not necessary Pin
Colin Angus Mackay2-Feb-09 2:59
MemberColin Angus Mackay2-Feb-09 2:59 
GeneralRe: Minor change means the base page is not necessary Pin
Gsaikrishna1-Feb-09 14:20
MemberGsaikrishna1-Feb-09 14:20 
GeneralRe: Minor change means the base page is not necessary Pin
-- Abhi --2-Feb-09 2:50
Member-- Abhi --2-Feb-09 2:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.