开发者

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

开发者 https://www.devze.com 2023-03-07 18:26 出处:网络
Does anyone know how can I check whether a session is empty or null in .net c# web-applications? Example:

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 displa开发者_JS百科y 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
}


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

精彩评论

暂无评论...
验证码 换一张
取 消