Jin Yong
Jin Yong

Reputation: 43778

how can I check whether the session is exist or with empty value or null in .net c#

Does anyone know how can I check whether a session is empty or null in .net c# web-applications?

Example:

I have the following code:

 ixCardType.SelectedValue = Session["ixCardType"].ToString();

It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??

Upvotes: 15

Views: 65647

Answers (3)

pickypg
pickypg

Reputation: 22332

Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.

string value = Session["ixCardType"] as string;

if (String.IsNullOrEmpty(value))
{
    // null or empty
}

Upvotes: 16

dlev
dlev

Reputation: 48596

You can assign the result to a variable, and test it for null/empty prior to calling ToString():

var cardType = Session["ixCardType"];
if (cardType != null)
{
    ixCardType.SelectedValue = cardType.ToString();
}

Upvotes: 1

SquidScareMe
SquidScareMe

Reputation: 3228

Something as simple as an 'if' should work.

 if(Session["ixCardType"] != null)    
     ixCardType.SelectedValue = Session["ixCardType"].ToString();

Or something like this if you want the empty string when the session value is null:

ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();

Upvotes: 25

Related Questions