C# 数据集与空值c的比较

C# 数据集与空值c的比较,c#,null,dataset,comparison,C#,Null,Dataset,Comparison,晚安 我似乎无法在空比较中使用我的数据集 我试图使一条语句在数据集为空的情况下继续我的代码 代码1: if ((string)dts.Tables[0].Rows[0]["RECID"] != null) ^只是跳过我的if,我知道它是空的,检查了我的手表,即使它是空的,仍然继续 代码2: long Recid = 0; Boolean checkrecid = long.TryParse((string)dts.Tables[0].Rows[0]["RECID"], out Recid)

晚安

我似乎无法在空比较中使用我的数据集 我试图使一条语句在数据集为空的情况下继续我的代码

代码1:

if ((string)dts.Tables[0].Rows[0]["RECID"] != null)
^只是跳过我的if,我知道它是空的,检查了我的手表,即使它是空的,仍然继续

代码2:

 long Recid = 0;
 Boolean checkrecid = long.TryParse((string)dts.Tables[0].Rows[0]["RECID"], out Recid);
 if (checkrecid == false)
^撞到我的屁股。我知道你可以使用TryCatch,但我不想使用它,因为它会让我的程序运行得更慢,而且它需要每天读10000行

错误:

A first chance exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
这意味着它什么也找不到,但我已经知道了

编辑:我不希望出现错误。任何以前的方法,在其他情况下都能工作,都会返回IndexOutfrange错误。我再加上这个。。 数据集由基于电话号码和其他数据的SQL server数据填充。 如果他找不到来自文本文件的电话号码,他将不返回任何内容,不返回行、列或任何内容

提前感谢,, DZ

您需要使用DBNull.Value而不是null

编辑:索引超出边界可能意味着根本没有行。尝试用以下内容替换您的if:

if (dts.Tables[0].Rows.Count > 0 && dts.Tables[0].Rows[0]["RECID"] != DBNull.Value)
{
}
这一行:

if ((string)dts.Tables[0].Rows[0]["RECID"] != null)
需要

if ((string)dts.Tables[0].Rows[0]["RECID"] != DBNull.Value)
或者您可以删除该支票:

Boolean checkrecid = long.TryParse((dts.Tables[0].Rows[0]["RECID"] ?? string.Empty), out Recid);
找到了

int strTables=dts.Tables[0].Rows.Count; 如果strTables==1{//代码在这里}


类型安全的替代方法是使用扩展方法。对于空字段,它将返回“null”而不是DBNull.Value

if (dts.Tables[0].Rows[0].Field<string>("RECID") != null)

stringdts.Tables[0].Rows[0][RECID]的字符串值是多少,我猜它不是空的,这就是您最初的检查不起作用的原因,可能是空字符串?因此,正在检查stringdts.Tables[0].Rows[0][RECID]!=可以吗?你能试试吗!dts.Tables[0]。行[0][RECID]改为DBNull?对于第一行,您是否尝试将其与string.Empty进行比较而不是null?行{System.Data.DataRowCollection}System.Data.DataRowCollection计数0 int两次没有人。。它仍然会给我errorYes,但是不要为了这个比较而转换为string`如果dts.Tables[0]。行[0][RECID]!=DBNull.values您是否删除了对Olivier提到的字符串的强制转换?我在回答中忘记了。我确实。。。在顶部添加了更多信息
if (dts.Tables[0].Rows[0].Field<string>("RECID") != null)