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

10

69

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

Sumatra answered 5/5, 2011 at 5:18 Comment(4)
Do you have the ADO.Net DataTable or by DataTable you mean the database table?Articulate
Is the data table just being used to supply the Total or is it being bound to another control, such as a gridView or repeater? Of you are purely extracting the total use Jonathan Woods suggestions below.Preserve
Do you know you have 5 rows, or could it be more or less?Gassing
thank you all for your effects. I got the answer.Sumatra
I
148

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();
Indurate answered 5/5, 2011 at 5:27 Comment(3)
He don't want filteration expression, he just want to calculate all rows amount. In your answer, Filteration expression means, it will compute sum where EmpId = 5.Slopwork
It asks for filter. I dont have any conditions to filter. I want to sum all the rows in the datatable.Sumatra
Jay Thanks for the solution. It reduces my number of line code.Danziger
P
39
 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();
Pardner answered 5/5, 2011 at 5:27 Comment(0)
S
15

You can do like..

DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);
Slopwork answered 5/5, 2011 at 5:30 Comment(0)
A
8

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
Articulate answered 5/5, 2011 at 5:28 Comment(0)
E
6

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();
Eldreda answered 29/2, 2016 at 8:26 Comment(0)
B
5
  public decimal Total()
    {
      decimal decTotal=(datagridview1.DataSource as DataTable).Compute("Sum(FieldName)","");
      return decTotal;
    }
Brita answered 8/11, 2012 at 4:59 Comment(0)
M
2

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

Megalith answered 26/2, 2016 at 13:37 Comment(0)
S
0

Try this

int sum = 0;
foreach (DataRow dr in dt.Rows)
{
     dynamic value = dr[index].ToString();
     if (!string.IsNullOrEmpty(value))
     { 
         sum += Convert.ToInt32(value);
     }
}
Subroutine answered 12/9, 2016 at 13:35 Comment(0)
V
0

I think this solves

using System.Linq;


(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))
Vestry answered 9/10, 2017 at 16:43 Comment(0)
A
0

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.

Ariellearies answered 26/7, 2021 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.