Quick Tutorial on using Session Variables

This is a down and dirty lesson on how to use Session Variables in C#. It won’t take long in your programming life that you will want an easy way to pass data from one page to another. Instead of using query strings (which also have their place in the world) or other methods, we can use these variables.

In your code behind file, wherever you want to add to the current session, you can simple add the line:

Session["yourVariableName"] = valueOfYourVariable; 

The “valueOfYourVariable” can pretty much be whatever you want. Strings, integers, variables, and so many other kinds of data.

On the page that is going to receive the data, pulling that information is as simple as using the following code:

string loadedData = (string)Session["yourVariableName"];

Obviously you need to cast your variable on the receiving page as the same data type as you saved it on the previous page, but other than that, it really is that simple to pass data between pages.

Any other complex data types you would just treat as you would normally once you load them.