How to create a session variable in ASP.NET

how to expire a session in asp net

Submitted by shantanu on Sat, 12/19/2009 - 13:38

  1. Define an ASP.NET web site.
  2. Create two pages within the site. The first page will contain an ASP.NET Web Form that will post back to itself and then redirect to the second page.
Note: The reason this example uses two pages is to prove that a session variable is available to a second, third, fourth, etc. page in the web site. Request variables, which are an alternative to session variables, cannot be carried over from an ASP.NET Web Form on one page to a second page
  • The first page must contain an ASP.NET Web Form that contains one <asp:textbox> server control and an <asp:button> server control. The "id" attribute of the textbox control should be set to "txtFirstName". The full code for the first page is provided below. Choose either C# or VB, depending on which language you've chosen for your ASP.NET site:

    This code pulls the contents from the <asp:textbox> server control named "txtFirstName" and creates a session variable named"sessFirstName" which is set equal to the contents of the server control. In other words, this code creates a session variable that holds the information the user enters on the form page.

    • ASP.NET (C#) - Page 1

  • In the second page, access Code view by choosing View > Code, and enter the code below to write the session variable contents to the page. Again, choose either C# or VB, depending on which language you've chosen for your ASP.NET site:
    • ASP.NET (C#) - Page 2

      And for Code behind Page write it as

  • Save, publish and test both pages. If you do not get the expected results, check the capitalization and spelling of the server controls, session variable and request variable.
  • How to retrieve session Id in Asp.Net

    Using session variables is very convenient and usually that is all you will need to maintain state from page to page. However, if you want to save the session state variable in a database for some reason to make sure something is visible only while a session is active (for instance if you want discussion posts to appear to the person posting as long as they are in their session but not to anyone else until you as the administrator approves the post). Here is the code to get the current SessionID.

    public static string TheSessionId()

    HttpSessionState ss = HttpContext.Current.Session;

    HttpContext.Current.Session["test"] = "test";


    Category: Forex

    Similar articles: