You are hereBlogs / shantanu's blog / How to create a session variable in ASP.NET

How to create a session variable in ASP.NET


By shantanu - Posted on 19 December 2009

  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

  3. 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
       <%@ Page Language="C#" %>
      <script  runat="server">    
      void Button1_Click(object sender, EventArgs e)    
      {    
      Session["sessFirstName"] = Request["txtFirstName"];    
      Response.Redirect("session2.aspx");    
      }
      </script>
      
      <html>
      	<head><title>Session Page 1</title></head>
      	<body>ASP.NET C# session variable and web form example - page 1
      	<form id="Form1" method="post" runat="server">
      	<p>first name:
      	<asp:TextBox id="txtFirstName" runat="server" />
      	</p>
      	
      	<p>
      	<asp:Button id="Button1" runat="server" Text="Submit" 
      	onClick="Button1_Click" />
      	</p>
      	</form>
      	</body>
      </html> 
  4. 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
       <%@ Page Language="C#" %>
      <html>
      	<head><title>Session Page 2</title></head>
      	<body>
      	<p>ASP.NET C# session variable and web form example - page 2</p>
      	<p>first name: <%=Session["sessFirstName"]%></p>
      	</body>
      </html> 

      And for Code behind Page write it as

    Session["sessFirstName"]='XYZ';

  5. 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";
    HttpContext.Current.Response.Write(ss.SessionID);
    return "ok";
}

Additional information

For more details on state management

 

Your post is really informative.  Everything works well except one change is to be made in your post which I have given below:

Don't write the following line in code view:

Session["sessFirstName"]='XYZ';

Because, it causes to hold the session variable in other pages as 'XYZ'. Rating of your post :4*.

Thanks, for liking the post. Yes I agree that Session["sessFirstName"]='XYZ'; would set a session variable having value 'XYZ'. 

And I intended to do so actually just for an example. 

 suppose i define an another textbox on Page 2 and want to auto put session variable value.in same text box.

 

Please Help??

 

 

The other day I was searching for ways to work with session variables, viewing session variable values which has been declared in different sessions and their sizes to be particular. I came accross the Asp.Net Web Profiler which displays variables and objects which has been declared in the application state, the current session state as well as in all user sessions. You can download it from www.aspwebprofiler.com

It also alows for drill down into object properties in order to detect large objects and optimizing them for memory usage.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <p> <span> <div> <h1> <h2> <h3> <h4> <h5> <h6> <img> <map> <area> <hr><br> <br /> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <em> <b> <u> <i> <strong><font> <del> <ins> <sub> <sup> <quote> <blockquote> <pre> <address> <code> <cite> <embed> <object> <param> <strike> <caption>
  • You can enable syntax highlighting of source code with the following tags: <c>, <cpp>, <csharp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <php>, <python>, <ruby>, <sql>, <tsql>, <vbnet>, <xml>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Lines and paragraphs break automatically.

More information about formatting options