结果的SqlCommand - 对象不能从DBNull的转换为其他类型 [英] SqlCommand result - Object cannot be cast from dbnull to other types

查看:1060
本文介绍了结果的SqlCommand - 对象不能从DBNull的转换为其他类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种的SqlCommand 总和客户端所有款项,但问题是在没有付款结果为空或0 - 我不知道。但我仍然收到同样的异常:对象不能从DBNull的转换为其他类型

I have got this SqlCommand that Sum all payments for client, but the issue is where there are no payments the result is null or 0 - I'm not sure. But I still receive the same exception: Object cannot be cast from dbnull to other types

什么异常或语句中可以修复它。

What Exception or if statement can fix it?

 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());

        }
    }



我仍然收到这个异常

I'm still receiving this exception:

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

object cannot be cast from dbnull to other types

我知道,这是低质量的问题,但我不知道我怎么能解决这个问题。

I know that this is low-quality question but I'm not sure how can I fix this.

感谢您的时间和答案。

推荐答案

您有两种选择。修正你的SQL语句,或转换

You have two options. Fix your SQL Statement, or your Convert.

SQL - 总结你的 SUM ISNULL

SQL - Wrap your SUM in an ISNULL:

SELECT ISNULL(SUM(payment), 0)

转换 - 比较它 DBNull.Value 第一:

Convert - Compare it to DBNull.Value first:

var result = sc.ExecuteScalar();
int intResult = result == DBNull.Value ? 0 : Convert.ToInt32(result);

这篇关于结果的SqlCommand - 对象不能从DBNull的转换为其他类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆