[英]Specified cast is not valid - System.InvalidCastException
I've read many of similar questions and tried several different things, but I do not understand why this is not working. 我已经阅读了许多类似的问题,并尝试了几种不同的方法,但是我不明白为什么这不起作用。 The column that is being summed is of the int type. 要求和的列为int类型。 I have tried casting to uint and int32. 我曾尝试将其转换为uint和int32。 I appreciate direction. 我感谢方向。 Thank you. 谢谢。
int i = 1;
int total=0;
while (i < 7)
{
string conString = @"Data Source=UATDB2\sqleuat;Initial Catalog=CVNee;User ID=appuser;Integrated Security=true";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT SUM(AMOUNT) FROM TRANSACTIONS_DETAIL2 WHERE TRANSACTIONS_DETAIL2.TRANS_TYPE =" + i + "AND TRANSACTIONS_DETAIL2.HOH_UPI = '185292000'";
int amt = ((int)cmd.ExecuteScalar());
//amt = cmd.ExecuteScalar();
if (i == 1)
{
total = total + amt;
}
if (i == 2)
{
total = total - amt;
}
if (i == 3)
{
total = total - amt;
}
if (i == 4)
{
total = total + amt;
}
if (i == 5)
{
total = total + amt;
}
if (i == 6)
{
total = total + amt;
}
connection.Close();
ViewBag.TotalBalance = total;
i++;
}
The illegal cast exception occurs, when ExecuteScalar
returns null
. 当ExecuteScalar
返回null
时,发生非法的强制转换异常。 You could either check if the result is null
before converting to int
, 您可以在转换为int
之前检查结果是否为null
。
object o = cmd.ExecuteScalar();
int result = o == null ? 0 : (int)o;
or you could use a nullable int int?
或者您可以使用可为空的int int?
which can also be checked if it has a value 也可以检查它是否具有值
int? result = (int?)cmd.ExecuteScalar();
if (!result.HasValue) result = 0;
or you could adjust your query to return 0
even if no matching rows are found. 或者,即使没有找到匹配的行,也可以将查询调整为返回0
。 The TSQL function COALESCE
checks if the first parameter is NULL
, if no it returns the value, if yes, it returns the value of the second parameter. TSQL函数COALESCE
检查第一个参数是否为NULL
,如果否则返回值,如果是,则返回第二个参数的值。
string query = "SELECT COALESCE(SUM(AMOUNT),0) FROM TRANSACTIONS_DETAIL2 WHERE TRANSACTIONS_DETAIL2.TRANS_TYPE =" + i + "AND TRANSACTIONS_DETAIL2.HOH_UPI = '185292000'";
If you call ExecuteScalar
, you might get null
or DBNull
in return, and you should check both. 如果调用ExecuteScalar
,则可能会返回null
或DBNull
,并且应同时检查两者。 You can first fill it into a variable of type object
, then check for DBNull.Value
and null
and react on this: 您可以先将其填充到类型为object
的变量中,然后检查DBNull.Value
和null
并对此做出反应:
int amt=0;
object amtUnchecked = cmd.ExecuteScalar();
if(amtUnchecked != DBNull.Value && amtUnchecked!=null)
amt=(int)amtUnchecked;
Or you change the SELECT
to return a sure zero: SELECT ISNULL(SUM(AMOUNT),0) ...
或者您更改SELECT
以返回肯定的零: SELECT ISNULL(SUM(AMOUNT),0) ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.