对指定的DataTable列进行求和统计

 

DataTable dt=GetData();
   DataRow dr = dt.NewRow();
   decimal de = 0;
   int iCount = 1;

   for(int i = iCount; i < dt.Columns.Count; i++)
   {
    ///需要对特殊字符进行转义,这里简略写,只对圆括号替换,其他遇到再说
    if(dt.Columns[i].ColumnName.IndexOf(")") > -1)
     dt.Columns[i].ColumnName = dt.Columns[i].ColumnName.Replace("(", "(").Replace(")", ")");

    de = dt.Compute("SUM([" + dt.Columns[i].ColumnName + "])", " 1 = 1 ") == System.DBNull.Value ? 0 :
     (decimal)dt.Compute("SUM([" + dt.Columns[i].ColumnName + "])", " 1 = 1 ");
    dr[i] = de;
   }
   dt.Rows.Add(dr);

   DataRow row = dt.Rows[dt.Rows.Count - 1];
   for(int i = dt.Columns.Count - 1; i > iCount ; i--)
   {
    if((decimal)(row[i]) == 0)
    {
     dt.Columns.Remove(dt.Columns[i]);
    }
   }
   dt.AcceptChanges();

   this.DataGrid1.DataSource = GetData();
   this.DataGrid1.DataBind();
   this.DataGrid1.Items[this.DataGrid1.Items.Count - 1].CssClass = "GridPage";
   this.DataGrid1.Items[this.DataGrid1.Items.Count - 1].Cells[0].Controls.Clear(); 

你可能感兴趣的:(.Net)