简体   繁体   中英

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

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:

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.

Thank you for your time and answers.

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

SQL - Wrap your SUM in an ISNULL :

SELECT ISNULL(SUM(payment), 0)

Convert - Compare it to DBNull.Value first:

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(',', '.'));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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