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"?
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();
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();
You can do like..
DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);
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
public decimal Total()
{
decimal decTotal=(datagridview1.DataSource as DataTable).Compute("Sum(FieldName)","");
return decTotal;
}
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();
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
Try this
int sum = 0;
foreach (DataRow dr in dt.Rows)
{
dynamic value = dr[index].ToString();
if (!string.IsNullOrEmpty(value))
{
sum += Convert.ToInt32(value);
}
}
I think this solves
using System.Linq;
(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))
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.
精彩评论