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*.

My developer is trying to convince me to move to .
net from PHP. I have always disliked the idea because of the costs.

But he's tryiong none the less. I've been using Movable-type on a number
of websites for about a year and am worried about switching to another platform.

I have heard great things about blogengine.net.
Is there a way I can transfer all my wordpress posts into it?
Any kind of help would be really appreciated!

Wow! After all I got a webpage from where I be able to truly
take useful facts regarding my study and knowledge.

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.

ASP.NET uses a visited composites rendering technique. During compilation, the template file is compiled into initialization code which builds a control tree representing the original template. Literal text goes into instances of the Literal control class, and server controls are represented by instances of a specific control class.

Programmers can also build custom controls for ASP.NET applications. Unlike user controls, these controls do not have an ASCX markup file, having all their code compiled 

 in first page \



        Session("Uname") = Trim(TextBox1.Text)

        Session("Pass") = Trim(TextBox2.Text)

        Mycon()

 

 

        Dim fname As String

        Dim lname As String

        '  Dim img As ImageField

 

 

 

 

 

        cmd.CommandText = "Select * from login2 where  Uname='" & Session("Uname") & "' and Pword='" & Session("Pass") & "'"

        Dr = cmd.ExecuteReader

        If Dr.Read Then

            fname = Dr.GetValue(1)

            lname = Dr.GetValue(0)

            ' img = Dr.GetValues(7)

 

 

 

            Session("fullname") = fname + lname

            ' Session("img") = img

 

            Response.Redirect("Docttest.aspx")

            cmd.CommandText = "select * from login2"

        Else

            Label4.Visible = True

            Dr.Close()

        End If

    End Sub

insecond page



        Label7.Text = Session("fullname")

        ' Image1.ImageUrl = Session("img")

 

 

waow! j'affectionne le template de votre blog.

The ߋperate of the inverter is to transform DC to Alternate Recent (AC).
Water oг hydro can be converted into electricity by
building dаmss aand surge tunnеls to make the ѡater turn large water turbines.

Zoning laws vwгy from city too city and tҺey determne whetҺer or
not you are allowed tοо do your ownn installation.

Hi,

This is Murali. I am new to ASP.Net. I want know how we will give session to Tree node for parent and child nodes.

Please give me example.

Regards,
Murali.

As thiѕ eneгǥy iis produced from natural resources they reducе tɦe costs of oρeration and usage.
These days tthеre are many options tyat neighborhoods
aгeе consіdering anոd personal homeowners have the choice оf instаlling ոnew
technologies within their houses too. There is ρlent of information available in the market nowadays, such
as thee resourϲes mentioned at the end of this article.

Hi

 

I dn't know knowledge about StateManagment(like Cookies,Sessions,Querystring) which purpose are using i want difference about dis and give proper examples 

in first page \

Session("Uname") = Trim(TextBox1.Text)
Session("Pass") = Trim(TextBox2.Text)
Mycon()

Dim fname As String
Dim lname As String
' Dim img As ImageField

cmd.CommandText = "Select * from login2 where Uname='" & Session("Uname") & "' and Pword='" & Session("Pass") & "'"
Dr = cmd.ExecuteReader
If Dr.Read Then
fname = Dr.GetValue(1)
lname = Dr.GetValue(0)
' img = Dr.GetValues(7)

Session("fullname") = fname + lname
' Session("img") = img

Response.Redirect("Docttest.aspx")
cmd.CommandText = "select * from login2"
Else
Label4.Visible = True
Dr.Close()
End If
End Sub
insecond page

Label7.Text = Session("fullname")
' Image1.ImageUrl = Session("img")

Hello...

Remarkable issues here. I am very glad to see your article.
Thanks a lott and I am taking a look aheazd to contact you.
Will you kindly drop me a e-mail?

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