2015-03-31 85 views
0

我想從我的數據庫中獲得int值。我有錯誤FormatException was unhandled Input string was not in a correct format.FormatException是未處理的輸入字符串格式不正確

我的代碼是

 string str = doc_cell.Text; 
     ulong a = Convert.ToUInt64(str); 
+0

str的值是什麼? 'ulong a = Convert.ToUInt64(「234」);'正在工作,例如。 'ulong a = Convert.ToUInt64(「ab」);'按預期拋出FormatException。您需要驗證您的用戶輸入。 – ibiza 2015-03-31 19:39:16

+0

嘗試這裏提到的解決方案http://stackoverflow.com/questions/10715238/format-exception-was-unhandled-input-string-was-not-in-a-correct-formats – user2526236 2015-03-31 19:42:15

回答

0
try 
{ 
    string str = doc_cell.Text; 
    ulong a = Convert.ToUInt64(str); 
} 
catch (FormatException) 
{ 
    MessageBox.Show("Error"); 
} 
+1

這是矯枉過正,使用TryParse代替。 – user2526236 2015-03-31 20:07:27

1

的問題就來了,因爲你的字符串轉換不UINT64,因爲這條線拋出異常。

你應該寫這樣的:

UInt64 a =0; 
bool isSuccess = UInt64.TryParse(str, out a); 

在這種情況下,您將有字符串的值在一,如果解析成功。如果解析不是,你將有一個0。