Session object question!

G

Guest

how do I check if the data in the session object is null before extracting it.
The following throws an error if the Session object has not already been
created.

string str = System.Web.HttpContext.Current.Session["abc"].ToString();

Thanks
 
S

Shiva

if (Session["abc"] == null)
{
// abc is null
}
else
{
// Use abc
}

how do I check if the data in the session object is null before extracting
it.
The following throws an error if the Session object has not already been
created.

string str = System.Web.HttpContext.Current.Session["abc"].ToString();

Thanks
 
S

Sacha

Hello...

You have to use an Object :

object o = System.Web.HttpContext.Current.Session["abc"] ;
string str = string.Empty ;

if (o != null)
str = o.ToString() ;
 
G

Guest

Thanks - I new it would be an easy answer!!!


Sacha said:
Hello...

You have to use an Object :

object o = System.Web.HttpContext.Current.Session["abc"] ;
string str = string.Empty ;

if (o != null)
str = o.ToString() ;



Tony said:
how do I check if the data in the session object is null before extracting it.
The following throws an error if the Session object has not already been
created.

string str = System.Web.HttpContext.Current.Session["abc"].ToString();

Thanks
 
K

Kevin Spencer

Thanks - I new it would be an easy answer!!!

Unfortunately, that was a klugy answer. You don't have to create an object
variable. All you need to do is test if the value is null before attempting
to assign it to a typed variable. Example:

string str; // declare your string
variable.
if (Session["abc"] != null) // Check if Session reference is null
str = (string) Session["abc"]; // Cast the Session object as a string
(or whatever it is) and assign it

This is much more efficient code. Also, it will work with any data type
stored in Session. Just change the cast.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
I get paid good money to
solve puzzles for a living


Tony said:
Thanks - I new it would be an easy answer!!!


Sacha said:
Hello...

You have to use an Object :

object o = System.Web.HttpContext.Current.Session["abc"] ;
string str = string.Empty ;

if (o != null)
str = o.ToString() ;



Tony said:
how do I check if the data in the session object is null before
extracting
it.
The following throws an error if the Session object has not already been
created.

string str = System.Web.HttpContext.Current.Session["abc"].ToString();

Thanks
 

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,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top