How to calculate the sum of the datatable column in asp.net?

I have a DataTable which has 5 columns:

  • ID
  • Name
  • Account Number
  • Branch
  • Amount

The DataTable contains 5 rows.

How can I show the sum of the Amount Column in a Label Control as "Total Amount"?


Solution 1:

To calculate the sum of a column in a DataTable use the DataTable.Compute method.

Example of usage from the linked MSDN article:

DataTable table = dataSet.Tables["YourTableName"];

// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", string.Empty);

Display the result in your Total Amount Label like so:

lblTotalAmount.Text = sumObject.ToString();

Solution 2:

 this.LabelControl.Text = datatable.AsEnumerable()
    .Sum(x => x.Field<int>("Amount"))
    .ToString();

If you want to filter the results:

 this.LabelControl.Text = datatable.AsEnumerable()
    .Where(y => y.Field<string>("SomeCol") != "foo")
    .Sum(x => x.Field<int>("MyColumn") )
    .ToString();

Solution 3:

You can do like..

DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);

Solution 4:

If you have a ADO.Net DataTable you could do

int sum = 0;
foreach(DataRow dr in dataTable.Rows)
{
   sum += Convert.ToInt32(dr["Amount"]);
}

If you want to query the database table, you could use

Select Sum(Amount) From DataTable