2016-08-30 80 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

相关问题