62,242
社区成员




/// <summary>
/// 数据源为DataTable的GridView列汇总器
/// </summary>
public class GridViewTotaller
{
#region Variables
private GridView gridView;
public string DispHTMLFormat = "{0}";
#endregion
#region Constructor
public GridViewTotaller(GridView gridView)
{
this.gridView = gridView;
}
#endregion
/// <summary>
/// 汇总Grid某一列的数据
/// </summary>
/// <param name="totalFld">要统计的列名</param>
/// <param name="cellIndex">要统计列的index</param>
/// <param name="format">格式,默认值为空</param>
public void Total<T>(String totalFld, Int32 cellIndex, String format) where T : struct, IFormattable
{
DataTable dt = (DataTable)gridView.DataSource;
if (dt.Rows.Count <= 0) return;
Object oValue = dt.Compute(String.Format("sum({0})", totalFld), "");
T value = (T)(oValue == DBNull.Value ? 0 : Convert.ChangeType(oValue, typeof(T)));
gridView.ShowFooter = true;
gridView.FooterRow.HorizontalAlign = HorizontalAlign.Right;
gridView.FooterRow.Cells[cellIndex].Text += String.Format(DispHTMLFormat, String.Format("{0}", value.ToString(format, null)));
}
public void Total<T>(String totalFld, Int32 cellIndex) where T : struct, IFormattable
{
Total<T>(totalFld, cellIndex, null);
}
/// <summary>
/// 汇总Grid某一列的数据
/// </summary>
/// <param name="grd">gridView</param>
/// <param name="totalFld">要汇总的字段</param>
/// <param name="cellIndex">要显示的单元格索引</param>
public static void TotalInfo(GridView grd, String totalFld, Int32 cellIndex)
{
GridViewTotaller totaller = new GridViewTotaller(grd);
totaller.Total<Decimal>(totalFld, cellIndex, "N2");
}
}