我有这样的代码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()
的可能的复制[无法投类型的对象 'System.DBNull' 输入“System.String \'](HTTP ://stackoverflow.com/questions/870697/unable-to-cast-object-of-type-system-dbnull-to-type-system-string) – Plutonix
我很想知道为什么它不能投射系统.DBNull到System.String给定一个字符串可以为null。为什么抛出异常而不是将字符串设置为空?在这种情况下,C#设计人员还认为人们会想要什么? –