在處理數(shù)據(jù)的時候如果數(shù)據(jù)庫里面的值為null,就會出現(xiàn)以上錯誤.
如:num = Convert.ToInt32(dtedit.Rows[k][i]),如果此時dtedit.Rows[k][i]的值為null就會出現(xiàn)這個錯誤.
解決辦法:
1.if (dtedit.Rows[k][i] == DBNull.Value)
num = 0;
else
num = Convert.ToInt32(dtedit.Rows[k][i]);
2.在讀取數(shù)據(jù)庫數(shù)據(jù)時判斷.如"Select IsNull(score,0) from score" 先把為null的數(shù)據(jù)表示為0
--------from:http://hi.baidu.com/fmhyht/blog/item/5edb5acf42090f3bf9dc61df.html
------------------
其實對于這個問題,還有一個辦法,還是不錯的:那就是用TryParse,
Convert.ToInt32 與 int.Parse 較為類似,實際上 Convert.ToInt32 內(nèi)部調(diào)用了 int.Parse:
- Convert.ToInt32 參數(shù)為 null 時,返回 0;
- int.Parse 參數(shù)為 null 時,拋出異常。
-
- Convert.ToInt32 參數(shù)為 "" 時,拋出異常;
- int.Parse 參數(shù)為 "" 時,拋出異常。
-
在處理數(shù)據(jù)的時候如果數(shù)據(jù)庫里面的值為null,就會出現(xiàn)以上錯誤.
如:num = Convert.ToInt32(dtedit.Rows[k][i]),如果此時dtedit.Rows[k][i]的值為null就會出現(xiàn)這個錯誤.
解決辦法:
1.if (dtedit.Rows[k][i] == DBNull.Value)
num = 0;
else
num = Convert.ToInt32(dtedit.Rows[k][i]);
2.在讀取數(shù)據(jù)庫數(shù)據(jù)時判斷.如"Select IsNull(score,0) from score" 先把為null的數(shù)據(jù)表示為0
--------from:http://hi.baidu.com/fmhyht/blog/item/5edb5acf42090f3bf9dc61df.html
------------------
其實對于這個問題,還有一個辦法,還是不錯的:那就是用TryParse,
Convert.ToInt32 與 int.Parse 較為類似,實際上 Convert.ToInt32 內(nèi)部調(diào)用了 int.Parse:
- Convert.ToInt32 參數(shù)為 null 時,返回 0;
- int.Parse 參數(shù)為 null 時,拋出異常。
-
- Convert.ToInt32 參數(shù)為 "" 時,拋出異常;
- int.Parse 參數(shù)為 "" 時,拋出異常。
-
- Convert.ToInt32 可以轉(zhuǎn)換的類型較多;
- int.Parse 只能轉(zhuǎn)換數(shù)字類型的字符串。
int.TryParse 與 int.Parse 又較為類似,但它不會產(chǎn)生異常,轉(zhuǎn)換成功返回 true,轉(zhuǎn)換失敗返回 false。最后一個參數(shù)為輸出值,如果轉(zhuǎn)換失敗,輸出值為 0。
public static int ParseInt(object obj)
{
int reInt = -1;
if (obj != null)
int.TryParse(obj.ToString(), out reInt);
return reInt;
}
- Convert.ToInt32 可以轉(zhuǎn)換的類型較多;
- int.Parse 只能轉(zhuǎn)換數(shù)字類型的字符串。
int.TryParse 與 int.Parse 又較為類似,但它不會產(chǎn)生異常,轉(zhuǎn)換成功返回 true,轉(zhuǎn)換失敗返回 false。最后一個參數(shù)為輸出值,如果轉(zhuǎn)換失敗,輸出值為 0。
public static int ParseInt(object obj)
{
int reInt = -1;
if (obj != null)
int.TryParse(obj.ToString(), out reInt);
return reInt;
}