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

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


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();


 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();


You can do like..

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