Hi,
How to sum DataTable column?
Thanks
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
SenthilkumarRank #387 · 6.5K reputationPosted Apr 12, 2012, 7:53 PM EDT
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);
Ifour Hiren61 reputationPosted Nov 3, 2016, 4:02 AM EDT
DataTable table; table = dataSet.Tables["YourTableName"]; // Declare an object variable. object sumObject; sumObject = table.Compute("Sum(Amount)", ""); above code helps you to make it working.Satyapriya NayakRank #47 · 31.5K reputationPosted Apr 12, 2012, 9:03 AM EDT
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
Satyapriya NayakRank #47 · 31.5K reputationPosted Apr 12, 2012, 9:50 AM EDT
con.Open();
string str = "select sum(amount)from order";
SqlCommand com = new SqlCommand(str, con);
txtamount.Text =com.ExecuteScalar().ToString ();
con.Close();
Thanks
vivek godse9 reputationPosted Jan 19, 2014, 8:19 PM EST
Rajesh Kumawat71 reputationPosted Dec 12, 2016, 12:20 AM EST
table.Columns.Add("Total", typeof(decimal)); foreach (DataRow row in table.Rows) { decimal rowSum = 0; foreach (DataColumn col in table.Columns) { if(!row.IsNull(col)) { string stringValue = row[col].ToString(); decimal d; if(decimal.TryParse(stringValue, out d)) rowSum += d; } } row.SetField("Total", rowSum); }