How to determine if a Session Variable exists?

S

Shapper

Hello,

How to determine if a Session Variable exists?

In Page_Load I need to check is Session("MyVar") Exists.
If it doesn't exist then I created it and give it a value:
Session("myVar") = "Value"

Thanks,
Miguel
 
N

Nawaz Ijaz

Simply do this..

if ( Session("MyVar") == "" )
{
Session("MyVar") = "Your Value"
}
 
K

Kevin Spencer

Ancient Zen problem:

If a Session variable is set, and there is no class to read it, does it
consume resources?

--
;-)

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.
 
Joined
Sep 21, 2011
Messages
2
Reaction score
0
session variable exists or not?

Its difficult to check whether a session name exists or not..
Because we cannot use a session instance name before it is being declared, means assigning the value to it. So it is better to use the following code. It is very bad programming. but if you want you can use it.

try
{
string data = Session["sessionIds"].tostring();
}
catch(Exception ex)
{
// Do your handling code. ie, if you want to set the session value set here.
}


the idea behind is that using the session variable before declaring the value will thow an error. By this we can make sure that the session variable is not existing.
If you want more specific just check what error throwing in this scenario and check whether the error is same as you required error and do the handling code.
make sure to check whether the error is not coming from any other reasons.
Usually the error will be "object reference not set to an instance of the object".
Hope this will help some one..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top