1

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?

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()

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user300485
  • 525
  • 5
  • 11
  • 24
  • Possible duplicate of [Unable to cast object of type 'System.DBNull' to type 'System.String\`](http://stackoverflow.com/questions/870697/unable-to-cast-object-of-type-system-dbnull-to-type-system-string) – Ňɏssa Pøngjǣrdenlarp Aug 30 '16 at 22:55
  • I'd be interested to know why it can't cast System.DBNull to System.String given that a string can be null. Why does it throw and exception rather than setting the string to null? What else did the C# designers think people would want to in this situation? – Paul McCarthy Apr 20 '17 at 15:37

1 Answers1

3

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

Shyju
  • 214,206
  • 104
  • 411
  • 497