Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 331
thevan Avatar asked May 05 '11 05:05

thevan


People also ask

How do you find the sum of a column in a DataTable?

sum() Sum the values in a data set. Fairly simply, this plug-in will take the data from an API result set and sum it, returning the summed value. The data can come from any data source, including column data, cells or rows.


2 Answers

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(); 
like image 179
Jay Riggs Avatar answered Oct 01 '22 17:10

Jay Riggs


 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(); 
like image 28
Thomas Avatar answered Oct 01 '22 17:10

Thomas