Sum a field within a datatable easily with the Compute method
File this one under the "who woulda thunk it!" section. There is a very simple and easy way to
sum the entire array of values for any given field within a datatable. If, for example, you need
to compute the total of all invoices in a given datatable, you can easily do so via the following
method:
Computing a total from a datafield
//Display the balanace of all invoices in the datatable
object oTotal = SelectedInvoices.Compute("SUM(InvoiceBalance)", "");
double dblInvoiceBalance = Double.Parse(oTotal.ToString());
txtInvoiceBalance.Text = dblInvoiceBalance.ToString("c");
That's it! The result will be the sum of the InvoiceBalance datafield. It's the easy way
to display computation results from a datatable and a method I use often. You can even use the
method to get averages and other computations against the fields. Pretty cool.
More information
Drop-In Code