Add aggregate rows to a table

protected Data.DataTable AggregatedTable(Data.DataTable TableToAggregate, string SortFieldName, string[] FieldsToAggregate)
{
 Data.DataTable ReturnTable = new Data.DataView(TableToAggregate, null, SortFieldName, Data.DataViewRowState.CurrentRows).ToTable;
 Data.DataColumn RowNumberColumn = new Data.DataColumn();
 RowNumberColumn.ColumnName = "Row~Number";
 RowNumberColumn.DataType = typeof(int);
 ReturnTable.Columns.Add(RowNumberColumn);
 Generic.List RowsToAddList = new Generic.List();
 do {
  Data.DataRow NewRow = ReturnTable.NewRow;
  ReturnTable.Rows.Add(NewRow);
  break; // TODO: might not be correct. Was : Exit Do
 } while (true);
 string LastMatch = "~";
 int LastRowNumber = new int();
 foreach (Data.DataRow ReturnRow in ReturnTable.Rows) {
  ReturnRow.Item("Row~Number") = ReturnTable.Rows.IndexOf(ReturnRow) * 2;
  LastRowNumber = ReturnRow.Item("Row~Number");
  if (LastMatch != "~") {
   if (LastMatch != ReturnRow.Item(SortFieldName).ToString) {
    Data.DataRow NewRow = ReturnTable.NewRow;
    NewRow.Item("Row~Number") = ReturnRow.Item("Row~Number") - 1;
    NewRow.Item("RowFont") = "Bold";
    if (!object.ReferenceEquals(ReturnTable.Compute("Sum(Grand_Inv_Total)", string.Format("(Exported = 'True') AND (Salesman1 = '{0}')", Server.HtmlEncode(LastMatch))), DBNull.Value)) {
     decimal Exported = ReturnTable.Compute("Sum(Grand_Inv_Total)", string.Format("(Exported = 'True') AND (Salesman1 = '{0}')", LastMatch));
     decimal ExportedPercent = Exported / ReturnTable.Compute("Sum(Grand_Inv_Total)", string.Format("(Salesman1 = '{0}')", LastMatch));
     NewRow.Item("Cust_Name") = "Exported: " + Exported.ToString("c") + Strings.StrDup(3, Strings.ChrW(160)) + ExportedPercent.ToString("p");
    }
    NewRow.Item(SortFieldName) = LastMatch;
    foreach (void AggregateField_loopVariable in FieldsToAggregate) {
     AggregateField = AggregateField_loopVariable;
     string FormatString = string.Format("Sum({0})", AggregateField);
     string FilterString = string.Format("{0} = '{1}'", SortFieldName, LastMatch.Replace("'", "''"));
     NewRow.Item(AggregateField) = ReturnTable.Compute(FormatString, FilterString);
    }
    RowsToAddList.Add(NewRow);
   }
  }
  LastMatch = ReturnRow.Item(SortFieldName).ToString;
 }
 foreach (Data.DataRow RowToAdd in RowsToAddList) {
  ReturnTable.Rows.Add(RowToAdd);
 }
 ReturnTable = new Data.DataView(ReturnTable, "[Row~Number] <> " + LastRowNumber, "Row~Number", Data.DataViewRowState.CurrentRows).ToTable;
 ReturnTable.Columns.Remove("Row~Number");
 return ReturnTable;
}

No comments:

Post a Comment