How to Determine a Session Variable Is Null or Empty in C#

Checking session if empty or not

Use this if the session variable emp_num will store a string:

 if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//The code
}

If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.

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

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

What is the best way to determine a session variable is null or empty in C#?

To follow on from what others have said. I tend to have two layers:

The core layer. This is within a DLL that is added to nearly all web app projects. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following:

public class SessionVar
{
static HttpSessionState Session
{
get
{
if (HttpContext.Current == null)
throw new ApplicationException("No Http Context, No Session to Get!");

return HttpContext.Current.Session;
}
}

public static T Get<T>(string key)
{
if (Session[key] == null)
return default(T);
else
return (T)Session[key];
}

public static void Set<T>(string key, T value)
{
Session[key] = value;
}
}

Note the generics for getting any type.

I then also add Getters/Setters for specific types, especially string since I often prefer to work with string.Empty rather than null for variables presented to Users.

e.g:

public static string GetString(string key)
{
string s = Get<string>(key);
return s == null ? string.Empty : s;
}

public static void SetString(string key, string value)
{
Set<string>(key, value);
}

And so on...

I then create wrappers to abstract that away and bring it up to the application model. For example, if we have customer details:

public class CustomerInfo
{
public string Name
{
get
{
return SessionVar.GetString("CustomerInfo_Name");
}
set
{
SessionVar.SetString("CustomerInfo_Name", value);
}
}
}

You get the idea right? :)

NOTE: Just had a thought when adding a comment to the accepted answer. Always ensure objects are serializable when storing them in Session when using a state server. It can be all too easy to try and save an object using the generics when on web farm and it go boom. I deploy on a web farm at work so added checks to my code in the core layer to see if the object is serializable, another benefit of encapsulating the Session Getters and Setters :)

How to determine a session variable contains data table is null or empty in C#

Your test is returning false because you are using a 'safe cast': as casting will return null if the conversion can't be made (see more on the C# guide here). Since you are trying to cast a datatable to a string, this will always return null, even when your session variable has a value.

To see the true nature of your problem, try converting them like this:

if(!string.IsNullOrEmpty((string)Session["tblItems"]))

This should thrown an exception, because you can't convert a datatable to a string like this. You will need to test for null like this:

if (Session["tblItems"] != null))

Update: having seen your comments, above, I've added a fuller example to explain what need to change. Your code should look more like this:

DataTable dt;

if (Session["tblItems"] != null))
{
dt = (DataTable)Session["tblItems"];
...
}
else
{
dt = new DataTable("tblItems1");
...
}

DataRow dr;
dr = dt.NewRow();
...

Note the changes I've made: initialise dt from session if there is a value, the cast will work in this case, and when it is null, construct a new one. You can then use the value in the section below without issue, because it will always have a value.

In addition, I would also recommend that you don't store your datatable in session at all, but rather just the values that you need.

How to check if session value is null or session key does not exist in asp.net mvc - 5

if(Session["TenantSessionId"] != null)
{
// cast it and use it
// The code
}

To Check Session is null or not

Try this

if(Session["Documentname"] != null)
{
var SearchDoc = (SearchDoc)Session["Documentname"];
var oDocumentID = SearchDoc.ClientID;
var Documentid = SearchDoc.DocumentID;

if (SearchDoc == null)
{
}

}

Checking if session is null causes exception

The problem was I wast trying to access a variable from a null session, so it could never check for the variable because the session was null.

The solution is as follows:

            if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session[Constants.SESSION_USER] = user;
}

This now checks the actual session, rather than the variable.

Check User Session is null or not

Try this

if( Session["User"] == null || string.IsNullOrEmpty(Session["User"].ToString()))
{
//return to login ;
}
else
{
// your default page
}


Related Topics



Leave a reply



Submit