How to store and clear session variables in C# asp.net

Session variables allow you to store global data for use across your website.  This data can be used for several applications, whether it be just displaying it on a page, or using it for comparison against data stored in a database.  There are a couple of ways to store session variables in C#.  In a specified action (like a button click or page load) use this code:

Session["variable name"] = source of variable;

For example, if you were storing a username typed into textbox1, you would use:

Session["username"] = TextBox1.Text;

An alternative way to perform the same action (where textbox1 is textboxt1’s id) is:

Session["username"] = Request["TextBox1"];

By default, these session variables are stored by the browser for 20 minutes.  This time interval can be altered in your web.config file.  If you wish to clear these variables manually you can do so with this code:

Session["variable name"] = null;

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • del.icio.us
  • Netvouz
  • description
  • ThisNext
  • MisterWong
  • Wists


About this entry