2012-03-01 120 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)