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

C#asp.netUser ControlsDatatable

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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 - C#

 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 - C#

You can do like..

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

Solution 4 - C#

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

Solution 5 - C#

  public decimal Total()
    {
      decimal decTotal=(datagridview1.DataSource as DataTable).Compute("Sum(FieldName)","");
      return decTotal;
    }

Solution 6 - C#

Compute Sum of Column in Datatable , Works 100%

lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();

if you want to have any conditions, use it like this

   lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();

Solution 7 - C#

You Can use Linq by Name Grouping

  var allEntries = from r in dt.AsEnumerable()
                            select r["Amount"];

using name space using System.Linq;

You can find the sample total,subtotal,grand total in datatable using c# at Myblog

Solution 8 - C#

Try this

int sum = 0;
foreach (DataRow dr in dt.Rows)
{
     dynamic value = dr[index].ToString();
     if (!string.IsNullOrEmpty(value))
     { 
         sum += Convert.ToInt32(value);
     }
}

Solution 9 - C#

I think this solves

using System.Linq;


(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))

Solution 10 - C#

If you're wanting to do this within your cshtml file, you can write it like this (including a LAMBDA expression):

<td><b>£@Model.Sum(i => i.Amount)</b></td>

You can remove the html tags, I just left them in to try and help with the example.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthevanView Question on Stackoverflow
Solution 1 - C#Jay RiggsView Answer on Stackoverflow
Solution 2 - C#ThomasView Answer on Stackoverflow
Solution 3 - C#Muhammad AkhtarView Answer on Stackoverflow
Solution 4 - C#FIre PandaView Answer on Stackoverflow
Solution 5 - C#Buntha KhinView Answer on Stackoverflow
Solution 6 - C#Arun Prasad E SView Answer on Stackoverflow
Solution 7 - C#Kutty Rajesh ValangaiView Answer on Stackoverflow
Solution 8 - C#NoWarView Answer on Stackoverflow
Solution 9 - C#Jonathan SantiagoView Answer on Stackoverflow
Solution 10 - C#DrowninGView Answer on Stackoverflow