繁体   English   中英

SqlCommand 结果 - 无法将对象从 dbnull 强制转换为其他类型

[英]SqlCommand result - Object cannot be cast from dbnull to other types

我有这个SqlCommand Sum all payments for client ,但问题是没有付款结果为空或 0 - 我不确定。 但我仍然收到相同的异常:无法将对象从 dbnull 强制转换为其他类型

什么 Exception 或 if 语句可以解决它?

 private void select_payments()
    {

        try
        {

            SqlCommand sc = new SqlCommand("SELECT SUM(payment) AS sumpayment FROM clientpayments WHERE subkey='" + selectid + "' AND year='" + selectedyear+ "'", con);

            con.Open();
            int result = Convert.ToInt32(sc.ExecuteScalar());
            con.Close();

            if (result != 0)
            {
                Convert.ToDecimal(textBox20.Text = result .ToString().Replace(',', '.'));
            }
        }

        catch (Exception ex)
        {
            MessageBox.Show(" " + ex.Message.ToString());

        }
    }

我仍然收到此异常:

对象不能从 dbnull 转换为其他类型

我知道这是一个低质量的问题,但我不确定如何解决这个问题。

感谢您的时间和答案。

你有两个选择。 修复您的 SQL 语句或转换。

SQL - 将您的SUM包裹在ISNULL

SELECT ISNULL(SUM(payment), 0)

转换 - 首先将其与DBNull.Value进行比较:

var result = sc.ExecuteScalar();
int intResult = result == DBNull.Value ? 0 : Convert.ToInt32(result);
object o = sc.ExecuteScalar();
con.Close();
if (o != null)
{
  int result = (int) o;
  if(result != 0)  Convert.ToDecimal(textBox20.Text = result .ToString().Replace(',', '.'));
}

暂无
暂无

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

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