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() ??
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();
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With