articles

Home / DeveloperSection / Articles / Sessions in ASP.Net

Sessions in ASP.Net

Sessions in ASP.Net

Dev Vrat Sahu 5816 28-Aug-2012

ASP.NET Session state provides a place to store values that will persist across page requests.  Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires

Creating Session

Session["Name"] = txtName.Text;Read Value from Session

StudentName.Text = Session["Name"].ToString();

Example

Here is the example which shows you to Create the Session and Store the data into it and also retrieve data from Session.

 

1.     Create the Default.aspx file and the design the following UI as below.

Sessions in ASP.Net

Add the following code on the Click Event Handler of Button (“Save info in Session”).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // This will store the values in Session
        Session["ID"] = txtID.Text;
        Session["Name"] = txtName.Text;
        Session["Course"] =cbCourse.Text;      
        Response.Redirect("RetriveInforamtiom.aspx");
    }
}
 

  2.     Now, add a new page and name it “RetriveInforamtiom.aspx” and design the following UI.

Sessions in ASP.Net

Now, on the Page_Load () event of “RetriveInforamtiom.aspx”, write the following codes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class RetriveInforamtiom : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Retriving stored data from Session
        StudentID.Text = Session["ID"].ToString();
        StudentName.Text = Session["Name"].ToString();
        StudentCourse.Text = Session["Course"].ToString();     
    }
} 

3.     Now, focus on the Default.aspx page and Run the Website. Provide the data for the required field and click on “Save info in Session” Button. It will store the data in session and further, it will be redirected to the “RetriveInforamtiom.aspx” page to retrieve and show data from Session. 

Here is the output of the above program. 

Sessions in ASP.Net


Updated 27-Dec-2019

Leave Comment

Comments

Liked By