我如何检查DataRow为null

时间:2016-04-06 00:32:11

标签: c# asp.net

我使用以下代码从数据库获取数据;

DataRow checkUser = vt.GetDataRow("select * from users where fb_ID='" + Profil.ID.ToString() + "'");
if (checkUser["fb_ID"] != null && checkUser["mail"] != null)
{
SignIn();
}

但是当DataRow返回null时,我得到:

  

对象引用未设置为对象的实例。

我尝试了一些解决方案。

首先,在How to check if Datarow value is null主题@Felipe Oriani讲述了该代码;

if (!row.IsNull("Int64_id"))
{
  // here you can use it safety
   long someValue = (long)row["Int64_id"];
}

我已尝试过我的代码;

DataRow checkUser = vt.GetDataRow("select * from users where fb_ID='" + Profil.ID.ToString() + "'");
if(!checkUser.IsNull("fb_ID") && !checkUser.IsNull("mail"))
{
SignIn();
}

但; Error Image

:/ 另外,@ mybirthname回答了这个问题。 他告诉" row [" ColumnName"]!= DBNull.Value,你也可以自己尝试这样的事情。一种方法是使用debuger!"我也尝试过,但代码也没有用。我得到了同样的错误。

其次,我尝试过null而不是#34;"并将其作为字符串和对象分配给变量。

最后,

if (!string.IsNullOrWhiteSpace(checkUser["fb_ID"].ToString()))
        {
            SignIn();
        } 

我在Stackoverflow上找到了代码,但我现在找不到网址了。无论如何,它也没有工作..

1 个答案:

答案 0 :(得分:0)

您必须首先检查DataRow,而不是单个列

DataRow checkUser = vt.GetDataRow("select * from users where fb_ID='" + Profil.ID.ToString() + "'");

if(checkUser != null)
{
    if (checkUser["fb_ID"] != null && checkUser["mail"] != null)
    {
        SignIn();
    }
}
相关问题