Share via


How do you store session variable in C#

Question

Monday, July 9, 2012 6:46 PM

I have 2 double and one boolean variable which unfortunately get reset every time I click a button on my website. I heard this can be mitigated by using session variables though I don't know how. I read somewhere that session variables can be stored using:

Session.Add("string", variable);

but I don't know how this actually can be used.

BTW, I'm a real beginner at this so if you could really explain what is going on and how exactly it can be implemented, that would help a lot.

All replies (3)

Monday, July 9, 2012 6:48 PM ✅Answered | 1 vote

Session["test"] = "";

But are you sure that sessions are the best option to you?If you want store informations that will be used only for 1 page, you can use ViewState, if you want share those informations between pages, perhaps you can use a Cache.

Take a look in google, about ViewState x Cache x Session, and look wich one fix better for you case.


Monday, July 9, 2012 6:52 PM ✅Answered

The Session class is similar to a dictionary of key type string and value type object. This allows you to store a variable of any type and refer to it later by name. So let's say you assign your variables as follows.

Session.Add("myvar1", false);
Session.Add("myvar2", 10);

In a later page view in the same session, you will have access to these values and can view them in the following manner

bool var1 = (bool)Session["myvar1"];
int var2 = (int)Session["myvar2"];

Monday, July 9, 2012 8:41 PM ✅Answered

Hi,

The session variables are exposed through the Session property of the Page object.
The  session variables are indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection.

This is how u assign a value to a session

Session["Test"] = "Am new to Session";

When u want to retrieve the value,

string abc = Session["Test"].ToString();

Lakshman