Hi,
How to sum DataTable column?
Thanks
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
SenthilkumarPosted Apr 12, 2012, 11:53 PM
There are many ways. You can use the LINQ, it will be less code and fast execution.
If you want to sum all the rows then
// Presumes a DataTable named "Orders" that has a column named "Total."
DataTable myTable;
myTable = myDataSet.Tables["Orders"];
// Declare an object variable.
object objSum;
objSum = myTable.Compute("Sum(Total)");
If you want to sum based on the condition then
// Presumes a DataTable named "Orders" that has a column named "Total."
DataTable myTable;
myTable = myDataSet.Tables["Orders"];
// Declare an object variable.
object objSum;
objSum = myTable.Compute("Sum(Total)", "EmpID = 5");
If you want to iterate the DataTable by every row then
DataTable dt = new DataTable();
int sum = 0;
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
sum += (int)dr[dc];
}
}
If you want to do by LINQ then
If untyped (replace int with the correct data type):
var sum = table.AsEnumerable().Sum(x=>x.Field
or:
var sum = table.AsEnumerable().Sum(x=>x.Field
If typed:
var sum = table.Sum(x=>x.SomeProperty);
Rajesh KumawatPosted Dec 12, 2016, 5:20 AM
Ifour HirenPosted Nov 3, 2016, 8:02 AM
vivek godsePosted Jan 20, 2014, 1:19 AM
Satyapriya NayakPosted Apr 12, 2012, 1:50 PM
con.Open();
string str = "select sum(amount)from order";
SqlCommand com = new SqlCommand(str, con);
txtamount.Text =com.ExecuteScalar().ToString ();
con.Close();
Thanks
Satyapriya NayakPosted Apr 12, 2012, 1:03 PM
DataTable table;
table = dataSet.Tables["YourTableName"];
// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", "");
Display the result in your Total Amount Label
lblTotalAmount.Text = sumObject.ToString();
Thanks