繁体   English   中英

System.InvalidCastException:无法将类型为System.DBNull的对象转换为类型为System.String的对象

[英]System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type '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行),则ExecuteScalar返回null ,如果尝试将其ExecuteScalar转换为字符串,则可能会得到null引用错误!

如果执行查询的结果实际上是NULL (SQL db表列中的NUll值),则ExecuteScalar将返回类型为System.DBNull的结果,如果尝试将其NUll为字符串,则会出现此错误。

在尝试投射(或对该对象执行其他任何操作)之前,请先执行null检查。

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

result!= null将返回false如果来自ExecuteScalar的结果为System.DBNull类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM