2012-03-01 117 views
2

Goodday与空的数值数据比较C#

我似乎无法用我的数据集在一个空比较 我试图做一个声明(以下尝试去),其中将只有当我继续我的代码数据集是空的。

代码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 

这意味着它找不到任何东西,但我已经知道了。

编辑:我不想要一个错误。任何以前的方法,都在其他情况下工作,返回索引范围错误。我将添加此.. 该数据集充满了来自基于电话号码和其他数据的SQL服务器的数据。 如果他找不到来自文本文件的电话号码,他将不会返回任何内容,也不会返回任何内容,也不会返回任何内容。

由于提前, DZ

+0

什么是'(串)dts.Tables [0] .Rows [0] [ “RECID”]',我猜测它的字符串值不为null这就是为什么你原来的支票没有工作,也许它的空弦?所以检查是否((字符串)dts.Tables [0] .Rows [0] [“RECID”]!=“”)'可能工作? – NominSim 2012-03-01 14:16:08

+0

你可以试试'if(!(dts.Tables [0])。行[0] [“RECID”]是DBNull))'而不是? – 2012-03-01 14:17:55

+0

对于第一行,你是否尝试过比较'string.Empty'而不是'null'? – user17753 2012-03-01 14:18:18

回答

0

找到了!

int strTables = dts.Tables[0].Rows.Count; if (strTables == 1){ //code goes here}

3

您需要使用DBNull.Value,而不是空

编辑:超出界限的指数可能意味着没有行的。尝试更换你的,如果有这样的:

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

是的,但不要转换为字符串为此比较。 '如果(dts.Tables [0] .Rows [0] [“RECID”]!= DBNull.Value) – 2012-03-01 14:20:24

+0

不工作waxmann ... – Dashzapp 2012-03-01 14:23:25

+0

您是否将铸件移除到Olivier提到的字符串?我在答案中忘记了这一点。 – Andrew 2012-03-01 14:29:35

0
if((string)dts.Tables[0].Rows[0]["RECID"] is DBNull) 
{ // will go here } 
2

这条线:

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

类型安全的替代方法是使用Field扩展方法。它将为空字段返回'null'而不是DBNull.Value。

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