user300485 user300485 - 3 months ago 22
C# Question

System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'

I have this code

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 = "";
}


I am getting this error. I know that I am getting NULL value as a return value. How do I need to resolve this Issue? Could anybody help me out?

Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
at ST_a9849ab5e79d483093f9802cd30cb2e7.csproj.ScriptMain.Main()

Answer

If the result of executing the query is empty (0 rows), ExecuteScalar returns null and if try to cast it to string you might get a null reference error!

If the result of executing the query is actually NULL (NUll value in your SQL db table column), ExecuteScalar will return a result of type System.DBNull and if try to cast it to string you will get this error.

Do your null check before trying to cast (or doing anything else on that object).

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

result!= null will return false If the result came from ExecuteScalar is of type System.DBNull