自动合计
目录
- SubTotal
- 实例
SubTotal
public class SubTotal
{
public decimal Sum { get; set; }
public int CellsPos { get; set; }
public string FieldName { get; set; }
// 将new的数组转为SubTotal数组对象
// 每个元素对象包含:
// CellsPos:第几列
// Sum:合计
// FieldName:字段名称
public static SubTotal[] InitSubTotal(string[] cellsList)
{
int count = cellsList.Length;//.GetUpperBound(0);
SubTotal[] total = new SubTotal[count];
for (int i = 0; i < count; i++)
{
string[] desc = cellsList[i].Split(',');
if (desc.Length == 2)
{
total[i] = new SubTotal()
{
CellsPos = int.Parse(desc[0]),
Sum = 0,
FieldName = desc[1]
};
}
}
return total;
}
// 根据所有的数据行和需要合计的栏位,进行计算
public static void ShowTotal(GridViewRowEventArgs e, SubTotal[] subTotals)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (SubTotal s in subTotals)
{
// 类似于,从容器中,取出与FieldName(key)属性对应的value
// 全部变量的对象,方法多次调用,修改了Sum的值
// 每一次行事件,调用一次
var data = DataBinder.Eval(e.Row.DataItem, s.FieldName);
if (data != null)
{
string str = data.ToString();
if (!string.IsNullOrEmpty(str)) // && isDigit(str))
{
decimal d = 0;
decimal.TryParse(str, out d);
s.Sum += d;
}
}
}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = " 合计:";
foreach (SubTotal s in subTotals)
{
e.Row.Cells[s.CellsPos].Text = s.Sum.ToString();
}
}
}
}
解读:
// 摘要:
// 在运行时计算数据绑定表达式。
//
// 参数:
// container:
// 表达式根据其进行计算的对象引用。 此标识符必须是以页的指定语言表示的有效对象标识符。
//
// expression:
// 从 container 对象到要放置在绑定控件属性中的公共属性值的导航路径。 此路径必须是以点分隔的属性或字段名称字符串,如 C# 中的 Tables[0].DefaultView.[0].Price
// 或 Visual Basic 中的 Tables(0).DefaultView.(0).Price。
//
// 返回结果:
// System.Object 实例,它是数据绑定表达式的计算结果。
//
// 异常:
// System.ArgumentNullException:
// expression 为 null 或修整后变成空字符串。
public static object Eval(object container, string expression);
实例
1.初始化对象:
//数字是栏位编号,从0开始,后面是栏位名称
SubTotal[] total = SubTotal.InitSubTotal(
new string[] {"4,Morning","5,Afternoon","6,OverTime","7,LeaveTime","8,Total"});
2.调用:
protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
Button btnDel = (Button)e.Row.FindControl("btnDel");
if (ibtn != null)
{
ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
}
}
//从0开始,栏位名称
SubTotal.ShowTotal(e, total);
}
3.给最后一行加样式: