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

2
  • Possible duplicate of Unable to cast object of type 'System.DBNull' to type 'System.String` Commented Aug 30, 2016 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? Commented Apr 20, 2017 at 15:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Still having the same problem.Thank you.
@user300485 Try testing for System.DBNull instead of null.
Yes got it System.DBNull.Value need to be used.. Thank you so much guys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.