繁体   English   中英

数据集与空值C#的比较

[英]Dataset comparison with Null Value c#

美好的一天

我似乎无法在Null比较中使用我的数据集,我试图做出一个声明(尝试如下),该语句仅在我的数据集为空时才继续执行我的代码。

代码1:

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

^仅跳过我的信息,如果我知道它为空(检查了我的手表),即使它为空,仍然继续。

代码2:

 long Recid = 0;
 Boolean checkrecid = long.TryParse((string)dts.Tables[0].Rows[0]["RECID"], out Recid);
 if (checkrecid == false)

^我的Tryparse崩溃。 我知道您可以使用Trycatching,但是我不想使用它,因为它会使我的程序运行缓慢,并且每天需要读取10000行。

错误:

A first chance exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll

意味着它什么也找不到,但我已经知道了。

编辑: 我不想出错。 所有在其他情况下都可以使用的先前方法,都将返回indexoutofrange错误。 我将添加此..数据集填充有基于电话号码和其他数据的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);

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

if (dts.Tables[0].Rows[0].Field<string>("RECID") != null)
if((string)dts.Tables[0].Rows[0]["RECID"] is DBNull)
{ // will go here }

找到了!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM