Rajkumar R

Rajkumar R

  • NA
  • 183
  • 220k

how to sum datatable field in asp.net[Invalid usage of aggregate function Sum() and Type: String]

Nov 5 2011 7:24 AM
   private void BindGrid()
    {
        // Set your connection String here
        SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Demo_eLogsVA4;Integrated Security=True");
        //Write a select Query
        cn.Open();
        string q = "Select Convert(nVarchar,A.Rec_No) CRec,A.Acc_Name Descr,A.Quantity Qty,Convert(nVarchar,A.Sell_Rate) SRate,Sell_CName Sname , Sell_CCode SCCode, Sell_CValue SCValue ,Convert(nVarchar,A.Quantity*A.Sell_Rate*Sell_CValue) SAmount, A.Service_Tax STax,Convert(nVarchar,(A.Quantity*A.Sell_Rate*Sell_CValue)* A.Service_Tax/100)Tax_Amount,Convert(nVarchar,((A.Quantity*A.Sell_Rate*Sell_CValue)+(A.Quantity*A.Sell_Rate*Sell_CValue)* A.Service_Tax/100)) as Net From eLogs_Invoice_Charges_Details A Where A.Invoice_Code='INV991'";
        DataSet dset = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(q, cn);        
        DataTable dtable = new DataTable();
        da.Fill(dtable);
        //Bind grid.
        GridView1.DataSource = dtable;
        object total = dtable.Compute("Sum(Net)", "");
        //object obj = dtable.Compute("SUM(Net)", string.Empty);
        double value =Convert.ToDouble(total) ;
        GridView1.DataBind();        
        GridView1.FooterRow.Cells[10].Text = value.ToString();
        cn.Close();
    }
I have the following error post solution for this

Invalid usage of aggregate function Sum() and Type: String.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.DataException: Invalid usage of aggregate function Sum() and Type: String.

Source Error:

Line 35:         //Bind grid. Line 36:         GridView1.DataSource = dtable; Line 37:         object total = dtable.Compute("Sum(Net)", ""); Line 38:         //object obj = dtable.Compute("SUM(Net)", string.Empty); Line 39:         double value =Convert.ToDouble(total) ;

Answers (3)