Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() ??

like image 613
Jin Yong Avatar asked May 24 '11 01:05

Jin Yong


2 Answers

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();
like image 139
SquidScareMe Avatar answered Sep 17 '22 18:09

SquidScareMe


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
}
like image 35
pickypg Avatar answered Sep 17 '22 18:09

pickypg