Assign and Access Session Variables from a Class in Asp.Net C# and Vb.Net

← PrevNext →

In this article, we will discuss about Session Variable. In addition, we will explore with examples on how we can assign a Session variable from an Asp.Net Class.

What is a Session Variable and why use it?

Whenever a user visits a website, the server assigns a new session for the user for a specific period. During this session, the server records specific information about the user till the user logs out or closes the browser.

The recorded sessions are used throughout the website (pages) until either the session is killed explicitly or it is over. Information, used in a particular session is stored using Session Variables.

Note: For every user, session data is stored separately.

E.g. Session(“mark”) = “a value”

We can assign a similar session in a Class too.

Assigning Session Design Mode (Asp.Net)

<%If Session("mark ") = “x” Then
    Some code here…
Else
    And here…
End If%>

Assigning Session from Code behind (C#)

protected void Form1_Load(object sender, System.EventArgs e)
{
    if (Session("mark ") == "x") {
        // Some code here…
    } else {
        // And here …
    }
}
Vb.Net
Protected Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles frmMemberList.Load
    If Session("mark ") = "x" Then
        ' Some code here…
    Else
        ' And here…
    End If
End Sub

The above Session is a type Variant since we have not assigned any specific type to it. What this means is any type of value can be assigned to Session("mark"). We can type-cast sessions i.e. a session variable can store values like String, Integer, Boolean and even DataSet.

Assign Session("mark") = True and while debugging check its type using Session(“mark”).GetType function.

Assign Session Variables in a Class

Its fairly simple using Sessions in a web page and it can also be used in a Class. Functions written in a Class always do some thing special. Like data hidding etc. And sometimes we need to assign Session variables in our Class itself. The process is slightly different. And this is how it should written.

System.Web.HttpContext.Current.Session("mark ") = "x".

Now check this Example

We have a login page with a textbox control, which accepts the E-mail ID and a button to submit it. The E-mail ID will be verified in a Class and the employee full name will be assigned into a session variable, so the user’s name can be displayed in all other pages.

Once the employee name is extracted from the database table and assigned to a session variable, the page will be re-directed to another page (EmployeeDetails.aspx), and diplay the value stored in the session variable.

As usual for this demo we’ll use the Employee Details table.

Create the Login Page (The Markup)
<!DOCTYPE html>
<html>
<head>
    <title>Assign Session Value from Asp.Net Class</title>
</head>
<body>
    <form id="form1" runat="server">
        <div style="font:15px Arial;">
        
            <h4>Employee Details</h4>
            
            Enter E-mail ID:
            <input runat="server" id="tbEmail" type="text" maxlength="100" />
            <input runat="server" id="btSubmit" type="submit" />
        </div>
    </form>
</body>
</html>
Code behind (C#)
using System;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        clsBusiness clsObj = new clsBusiness();

        if (!string.IsNullOrEmpty(tbEmail.Value))
        {
            // CAll A FUNCTION IN THE CLASS, FETCH AND ASSING SESSION VARIABLE.

            if (clsObj.GetUserDetails(tbEmail.Value) == true)
            {
                // WE HAVE FETCHED EMPLOYEE DETAILS, NOW REDIRECT TO ANOTHER PAGE.
                // THE REDIRECTED PAGE WILL SHOW THE FETCHED DETAILS USING VALUE FROM A SESSION VARIABLE.
                Response.Redirect("EmployeeDetails.aspx");
            }
        }

    }
}
Vb.Net
Option Explicit On
Imports System.Data                        ' FOR "DataTable"
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Dim clsObj As New clsBusiness

    Protected Sub btSubmit_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles btSubmit.ServerClick

        If Trim(tbEmail.Value) <> "" Then

            ' CAll A FUNCTION IN THE CLASS, FETCH AND ASSING SESSION VARIABLE.
            If clsObj.GetUserDetails(Trim(tbEmail.Value)) = True Then

                ' WE HAVE FETCHED EMPLOYEE DETAILS, NOW REDIRECT TO ANOTHER PAGE.
                ' THE REDIRECTED PAGE WILL SHOW THE FETCHED DETAILS USING
                ' VALUE FROM A SESSION VARIABLE.

                Response.Redirect("EmployeeDetails.aspx")
            End If
        End If
    End Sub
End Class
The Class which Assigns the Session Variable (clsBusiness)
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class clsBusiness
{
    public bool GetUserDetails(string sEmail)
    {
        // SET THE CONNECTION STRING.
        string sCon = "Data Source=dna;Persist Security Info=False;" +
            Integrated Security=SSPI;" + 
            "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=demo;Connect Timeout=30;";

        using (SqlConnection con = new SqlConnection(sCon))
        {
            using (SqlCommand cmd = new SqlCommand(
            "SELECT EmpName FROM dbo.EmployeeDetails WHERE Email = '" + 
                sEmail.ToString() + "'"))
            {
                SqlDataAdapter sda = new SqlDataAdapter();
                try {
                    cmd.Connection = con;
                    con.Open();
                    sda.SelectCommand = cmd;

                    DataTable dt = new DataTable();
                    sda.Fill(dt);

                    // ASSIGNING VALUE TO SESSION VARIABLE.
                    System.Web.HttpContext.Current.Session["UserFullName"] = 
                        dt.Rows[0]["EmpName"];
                }
                catch (Exception ex) { 
                    //
                }
                return true;
            }
        }
    }
}
Vb.Net
Option Explicit On
Imports Microsoft.VisualBasic
Imports System.Data         ' FOR "DataTable"
Imports System.Data.SqlClient

Public Class clsBusiness
    ' CHECKS FOR THE EMPLOYEE DETAILS AND ASSIGN SESSION.
    
    Public Function GetUserDetails(ByVal sEmail As String) As Boolean

        ' SET THE CONNECTION STRING.
        Dim sCon As String = "Data Source=dna;Persist Security Info=False; & _
            "Integrated Security=SSPI;" & _
            "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=demo;Connect Timeout=30;"

        Using con As SqlConnection = New SqlConnection(sCon)
            Using cmd As SqlCommand = _
                New SqlCommand("SELECT EmpName FROM dbo.EmployeeDetails " & _
                    "WHERE Email = '" & Trim(sEmail) & "'")

                Dim sda As SqlDataAdapter = New SqlDataAdapter
                Try
                    cmd.Connection = con : con.Open()
                    sda.SelectCommand = cmd

                    Dim dt As DataTable = New DataTable
                    sda.Fill(dt)

                    ' ASSIGNING VALUE TO SESSION VARIABLE.
                    System.Web.HttpContext.Current.Session("UserFullName") = 
                        dt.Rows(0).Item("EmpName")

                    Return True
                Catch ex As Exception
                    '
                End Try
            End Using
        End Using
    End Function
End Class
The Re-directed Page (EmployeeDetails.aspx)
Markup
<html>
<head>
    <title>Showing Session Value</title>
</head>
<body>
    <form id="form1" runat="server">
    
        <div style="font:15px Arial;">
            <h4>Value Fetched From A Session Variable</h4>
            Employee Name: <asp:Label runat="server" ID="lblEmpName"></asp:Label>
        </div>
        
    </form>
</body>
</html>
C#
using System;

public partial class EmployeeDetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblEmpName.Text = Session["UserFullName"].ToString(); // SHOW THE EMPLOYEE'S NAME.
    }
}
Vb.Net
Option Explicit On

Partial Class EmployeeDetails
    Inherits System.Web.UI.Page

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
        Handles form1.Load
         ' SHOW THE EMPLOYEE'S NAME.
        lblEmpName.Text = Trim(Session("UserFullName"))
    End Sub
End Class

How long with a Session Last?

By default a Session lasts for 20 minitues if there is no activity from the user on that web site. Session time can be increased or decreased from the server if required.

System.Web.HttpContext.Current.Session.Timeout = 1, in the Class.

Or

Session.Timeout = 1, in web page code behind.

Now the Session will expire after 1 minute.

Well, that's it. Thanks for reading.

← PreviousNext →