Search code examples
c#datatable

Datatable.Compute returns what?


I have a simple Cart DataTable.

static DataTable dtItem = new DataTable();

dtCart.Columns.Add("Code", typeof(string));
dtCart.Columns.Add("Name", typeof(string));
dtCart.Columns.Add("Price", typeof(double));
dtCart.Columns.Add("Amount", typeof(double));
dtCart.Columns.Add("Total", typeof(double), "Price*Amount");

And i want to check if there is no item in the cart by counting the amount.

if (Convert.ToInt32(dtCart.Compute("SUM(Amount)", "")) == 0)
{
    MessageBox.Show("No item in the cart!");
    return;
}

But if there is no rows in the cart, the Compute() returns a null value that cannot be converted.

Then i added :

if (dtCart.Compute("sum(Amount)", "") == null)
{
    MessageBox.Show("No item in the cart!");
    return;
}

And somehow it passed the if, no MessageBox Shown.


Solution

  • When using ADO.NET, database nulls are represented by DBNull.Value, so that is what Compute will return in that case:

    var totalAmount = dtCart.Compute("SUM(Amount)", string.Empty);
    
    if (totalResult == DBNull.Value || Convert.ToDouble(totalAmount) == 0.0)
    {
        // ...
    }
    

    Of course, given that you have no choice but to test two conditions, you could just test whether there are any rows first:

    if (dtCart.Rows.Count == 0 ||
        Convert.ToDouble(dtCart.Compute("SUM(Amount)", string.Empty)) == 0.0)
    {
        // ...
    }