我需要计算总金额。我的销售发票看起来像
如何将金额相加以在总销售额中显示?
int orderNo = 234;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] {
new DataColumn("QUANTITY", typeof(string)),
new DataColumn("UNIT", typeof(string)),
new DataColumn("DESCRIPTION", typeof(string)),
new DataColumn("UNIT PRICE", typeof(string)),
new DataColumn("AMOUNT", typeof(string))});
while (dr.Read()) {
finalam = dr.GetDouble(0);
quantity = dr.GetInt32(1);
unit = dr.GetString(2);
description = dr.GetString(3);
unitpr = dr.GetDouble(4);
dt.Rows.Add(quantity, unit, description, unitpr, totalam);
double sum = 0.0;
Session["FinalAmount"]= sum += finalam;
}
foreach (DataColumn column in dt.Columns)
{
sb.Append("<th size='small' align='center'><b>");
sb.Append(column.ColumnName);
sb.Append("</th></b>");
}
答案 0 :(得分:2)
让数据库计算总和(使用SQL $desc = preg_replace('/\[\/?=vc/\.*?\]/','', $desc);
方法),这比首先将所有行都拉入内存然后循环遍历它们要快得多。
SUM
答案 1 :(得分:1)
这应该这样做:
double sum = 0.0;
while (dr.Read()) {
finalam = dr.GetDouble(0);
quantity = dr.GetInt32(1);
unit = dr.GetString(2);
description = dr.GetString(3);
unitpr = dr.GetDouble(4);
dt.Rows.Add(quantity, unit, description, unitpr, totalam);
sum += finalam;
}
Session["FinalAmount"] = sum;
只需要在循环外声明sum
,否则每次循环运行时其值都会重置为0。同样地,将变量添加到Session应该只在过程结束时完成一次。
我个人还建议您将变量存储在表中作为正确的类型,而不是字符串。