【问题标题】:How to read a bit value from a DB and set the value as a Boolean session variable if not null如何从数据库中读取位值并将该值设置为布尔会话变量(如果不为空)
【发布时间】:2020-03-03 07:01:13
【问题描述】:

如何将从数据库读取的位数据库值设置为布尔会话变量,该变量将从第 1 页传递到第 2 页。在第 2 页上,我需要在读取其值之前验证该变量不为空. “管理员”列是位类型。

page1.aspx:

bool IsAdmin = (bool)reader["Administrator"]; // getting Specified cast is not valid here if null
if (IsAdmin)
{
     Session["IsAdministrator"] = true;
}
else
{
    Session["IsAdministrator"] = false;
}

page2.aspx:

//This is how I would check that the variable is not null if it were a string, how do I check the same for a Boolean?
Boolean isAdmin;
if (!string.IsNullOrEmpty(Session["IsAdministrator"] as string))
{
    isAdmin = (bool)(Session["IsAdministrator"]);
}

【问题讨论】:

  • 你能澄清你的问题吗?

标签: c# asp.net


【解决方案1】:

page1.aspx:

/* if reader["Administrator"] is null, assign false to IsAdmin, alternatively you could throw 
and exception if you are not ok with setting false if the field is NULL on the db */
bool IsAdmin = reader["Administrator"] as bool? ?? false;
if (IsAdmin)
{
     Session["IsAdministrator"] = true;
}
else
{
    Session["IsAdministrator"] = false;
}

page2.aspx:

// You could simplify
Boolean isAdmin = Session["IsAdministrator"] as Boolean? ?? false;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2019-06-14
    • 2013-08-21
    • 1970-01-01
    • 2017-05-30
    • 2011-08-21
    相关资源
    最近更新 更多