Search code examples
c#vb.netdevexpressxtragrid

Gridview get difference between two sums


I'm using devexpress XtraGrid control. My problem is the following: I want to get the sum of the first column, and then the second column. I eventually want to subtract the sum of the first column of the sum of the second columns and to display the grid in the footer ...

Sum1Columns - Sum2Columns = balance

And then show balance on data grid control - footer (below the 1column)

dgvVIEW.Columns(1).Name = "PROMDUGU"
dgvVIEW.Columns(1).Caption = "1COLUMN"
dgvVIEW.Columns(1).Visible = True
dgvVIEW.Columns(1).DisplayFormat.FormatType = FormatType.Numeric
dgvVIEW.Columns(1).DisplayFormat.FormatString = "c2"
dgvVIEW.Columns(1).SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Custom
dgvVIEW.Columns(1).SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum
dgvVIEW.Columns(1).SummaryItem.DisplayFormat = "SUM= {0:n2}"

dgvVIEW.Columns(2).Name = "PROMPOTR"
dgvVIEW.Columns(2).Caption = "2COLUMN"
dgvVIEW.Columns(2).Visible = True
dgvVIEW.Columns(2).DisplayFormat.FormatType = FormatType.Numeric
dgvVIEW.Columns(2).DisplayFormat.FormatString = "c2"
dgvVIEW.Columns(2).SummaryItem.SummaryType =  DevExpress.Data.SummaryItemType.Sum
dgvVIEW.Columns(2).SummaryItem.DisplayFormat = "Sum= {0:n2}"

Solution

  • Add another summary field to 2nd column and set its type to custom.

    dgvVIEW.Columns(2).Summary.Add(new GridColumnSummaryItem(SummaryItemType.Custom, "customBalance", "Balance= {0:c2}"));
    

    Then handle CustomSummaryCalculate event.

    private void dgvVIEW_CustomSummaryCalculate(object sender, CustomSummaryEventArgs e) {
        if (e.SummaryProcess == CustomSummaryProcess.Start) {
          this.sum1 = 0; // <--- class member !
          this.sum2 = 0; // <--- class member !
          return; 
        }
    
        if (e.SummaryProcess == CustomSummaryProcess.Calculate) {
          if (e.Item.FieldName == "PROMDUGU" {
            this.sum1 += Convert.ToDecimal(e.FieldValue);
            return;
          } 
          if (e.Item.FieldName == "PROMPOTR" {
            this.sum2 += Convert.ToDecimal(e.FieldValue);
            return;
          } 
          return; 
        }
    
    
        if (e.SummaryProcess == CustomSummaryProcess.Finalize && e.Item.FieldName == "customBalance") {
           e.TotalValue = sum1 - sum2;
        }
    }