2016-08-30 79 views
0

我有這樣的代碼System.InvalidCastException:無法投類型的對象'System.DBNull爲鍵入「System.String」

SqlCommand objcmd1 = new SqlCommand("select r.login_Id from XYZ where a.logonid = @uId", myADONETConnection); 
objcmd1.Parameters.Add("@uId", SqlDbType.VarChar).Value = dr[0].ToString(); 

returnUserId = (string)objcmd1.ExecuteScalar(); 

if (returnUserId != null) 
{ 
    adid = returnUserId.ToString(); 
} 
else 
{ 
    adid = ""; 
} 

我得到這個錯誤。我知道我得到NULL值作爲返回值。我該如何解決這個問題?有人能幫我嗎?

System.Reflection.TargetInvocationException:調用的目標引發了異常。 ---> System.InvalidCastException:無法將類型爲「System.DBNull」的對象轉換爲鍵入「System.String」。
在ST_a9849ab5e79d483093f9802cd30cb2e7.csproj.ScriptMain.Main()

+0

的可能的複製[無法投類型的對象 'System.DBNull' 輸入「System.String \'](HTTP ://stackoverflow.com/questions/870697/unable-to-cast-object-of-type-system-dbnull-to-type-system-string) – Plutonix

+0

我很想知道爲什麼它不能投射系統.DBNull到System.String給定一個字符串可以爲null。爲什麼拋出異常而不是將字符串設置爲空?在這種情況下,C#設計人員還認爲人們會想要什麼? –

回答

2

如果執行查詢的結果爲空(0行),ExecuteScalar回報null,如果嘗試將其轉換爲字符串,你可能會得到一個空引用錯誤!

如果執行查詢的結果實際上是NULL(在你的SQL數據庫表列NUll值)的ExecuteScalar會返回System.DBNull類型的結果,如果嘗試將其轉換爲字符串,你會得到這個錯誤。

在嘗試投射(或對該物體做其他事情)之前,請檢查null

string returnUserId = string.Empty; 
var result = objcmd1.ExecuteScalar(); 
if (result!= null) 
{ 
    returnUserId = (string) result; 
} 

result!= null將返回false如果結果來自的ExecuteScalar傳來的類型爲System.DBNull

+0

仍然有同樣的問題,謝謝。 – user300485

+1

@ user300485嘗試測試'System.DBNull'而不是'null'。 – itsme86

+0

是的,它需要使用System.DBNull.Value ..非常感謝你們。 – user300485

相關問題