# Grouping and Aggregates in a Blazor Grid

URL: https://flexcoreui.com/demo/grid/grouping  
Section: Data Grid  
Controls: GridControl, GridColumn, AggregateColumn  
Keywords: grouping, group by, aggregates, totals, footer sum, row grouping

Group a Blazor grid by any column, in code or by dragging a header, and show sums, averages and counts in captions and footers.

## Documentation

### Grid

| Name | Type | Default | Description |
|---|---|---|---|
| AllowGrouping | bool | false | Required for any grouping. Shows the group bar, lets a header be dragged onto it and a chip be removed, and makes GroupColumns take effect; off, the grid stays flat. |
| GroupColumns | List<string>? | null | Fields to group by on first render, outermost first. A new list instance re-syncs the groups. |
| HideGroupedColumns | bool | true | Hides a grouped column from the data rows. False keeps it in place as well. |
| ShowGroupCount | bool | false | Appends (n items) to each caption. |
| DefaultGroupsCollapsed | bool | false | Start with every group collapsed. |
| ShowGroupExpandCollapse | bool | true | Shows the Expand All / Collapse All toggle in the group bar. |
| GroupExpandIconStyle | GroupExpandIconStyle | GroupExpandIconStyle.PlusMinus | PlusMinus boxes or Triangle chevrons on the caption rows. The expand-icon template and glyph parameters override the preset. |
| GroupHeaderTextSelector | Func<string, string, IReadOnlyList<TValue>, string>? | null | Replaces the caption text. Receives the field, the key as text and the group's rows; the key itself, and so collapse state, is unchanged. |
| AggregateRows | List<AggregateRow>? | null | What to compute and where to print it; the two tables below. |
| GroupedColumnColor / GroupItemTextColor / GroupTotalTextColor | string | "" | Optional CSS colors for the grouped values in caption rows and chips, the caption text, and the aggregate values. Empty inherits. |
| ShowRowCountInFooter | bool | false | Prints the row count of the complete filtered result in the footer, not of the rendered window or page. |
| EnableGroupedRowWindowing | bool | true | Windows the rows of a grouped grid the way a flat grid is windowed. Off renders every row. |
| GroupFooterTemplate | RenderFragment<object>? | null | Declared, but GridControl never reads it. |
| GroupFootersAlwaysVisible | bool | false | Declared, but GridControl never reads it. |

### Column

| Name | Type | Default | Description |
|---|---|---|---|
| AllowGrouping | bool | true | False keeps this column out of grouping: its header cannot be dropped on the bar, its header menu offers no group command, and GroupByColumnAsync ignores it. |

### Row

| Name | Type | Default | Description |
|---|---|---|---|
| Columns | List<AggregateColumn> | new() | The aggregates of this row. |
| ShowInGroupFooter | bool | true | A row of values under each group, aligned with the columns. |
| ShowInFooter | bool | false | The same row after all data. |
| ShowInGroupCaption | bool | false | Every value inline in the caption, after the group name and the count. |
| ShowInGroupHeader | bool | false | An extra aligned row at the top of each group, under the caption. |

### Agg

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string | "" | The property to aggregate. |
| Type | AggregateType | AggregateType.Sum | Sum, Average, Count, Min or Max. |
| Format | string? | null | .NET format applied to the number, such as C2 or N0. |
| FooterTemplate | string | "{value}" | Text with {value} for the number, used wherever no more specific template is set. The words Total:, Sub Total: and Grand Total: are removed from the result. |
| GroupFooterTemplate | string? | null | Template for group footers; falls back to FooterTemplate. |
| GroupCaptionTemplate | string? | null | Template for captions and the group header row; falls back to FooterTemplate. |

### Events

| Name | Type | Description |
|---|---|---|
| Grouping | GroupEventArgs | Before a field is grouped by drag or GroupByColumnAsync; Field names it and Cancel refuses. Not raised for GroupColumns. |
| Grouped | GroupEventArgs | After the group is added. |
| Ungrouping | GroupEventArgs | Before a field is ungrouped from its chip, the bar's Clear All or UngroupColumnAsync; Cancel refuses. ClearGroupingAsync raises neither this nor Ungrouped. |
| Ungrouped | GroupEventArgs | After the group is removed. |

### Methods

| Name | Type | Description |
|---|---|---|
| GroupByColumnAsync(string field) | Task | Adds a group, with the events and the column's AllowGrouping honored. |
| UngroupColumnAsync(string field) | Task | Removes a group, with the events. |
| ClearGroupingAsync() | Task | Removes every group without raising the events. |
| ExpandAllGroupAsync() | Task | Expands every group and re-renders. |
| CollapseAllGroupAsync() | Task | Marks every group collapsed; the change shows on the next render. |

## Examples

### Package costs

```razor
@using Fx.ControlKit.Grid

<div class="catalog">
<GridControl TValue="PackageCostLine"
             DataSource="@_costLines"
             AllowSelection="true"
             AllowSorting="true"
             AllowFiltering="true"
             AllowGrouping="true"
             AllowResizing="true"
             AllowColumnReorder="true"
             ShowSearchBar="true"
             Height="420px"
             AggregateRows="_sums">
    <GridColumnsBase>
        <GridColumn Field="@nameof(PackageCostLine.Season)"      HeaderText="Season"     Width="90px" />
        <GridColumn Field="@nameof(PackageCostLine.CostGroup)"   HeaderText="Cost group" Width="140px" />
        <GridColumn Field="@nameof(PackageCostLine.Supplier)"    HeaderText="Supplier"   Width="190px" />
        <GridColumn Field="@nameof(PackageCostLine.Description)" HeaderText="Service"    Width="240px" />
        <GridColumn Field="@nameof(PackageCostLine.Qty)"         HeaderText="Qty"        Width="70px"
                    Type="ColumnType.Number" Format="N0" TextAlign="TextAlign.Right" />
        <GridColumn Field="@nameof(PackageCostLine.Unit)"        HeaderText="Unit"       Width="80px" />
        <GridColumn Field="@nameof(PackageCostLine.Rate)"        HeaderText="Net rate"   Width="110px"
                    Type="ColumnType.Number" Format="C2" TextAlign="TextAlign.Right" />
        <GridColumn Field="@nameof(PackageCostLine.Total)"       HeaderText="Total"      Width="120px"
                    Type="ColumnType.Number" Format="C2" TextAlign="TextAlign.Right" />
        <GridColumn Field="@nameof(PackageCostLine.RateBasis)"   HeaderText="Rate basis" Width="100px" />
    </GridColumnsBase>
</GridControl>
</div>
```

```csharp
// Package cost lines: sums in group footers and the grid footer, no initial group.
private List<PackageCostLine> _costLines = DemoData.GeneratePackageCostLines(60);

private List<AggregateRow> _sums = new()
{
    new AggregateRow
    {
        ShowInGroupFooter = true,
        ShowInFooter = true,
        Columns = new()
        {
            new AggregateColumn { Field = nameof(PackageCostLine.Qty),   Type = AggregateType.Sum, Format = "N0", FooterTemplate = "Σ {value}", GroupFooterTemplate = "Σ {value}" },
            new AggregateColumn { Field = nameof(PackageCostLine.Total), Type = AggregateType.Sum, Format = "C2", FooterTemplate = "Σ {value}", GroupFooterTemplate = "Σ {value}" },
        }
    }
};

// Data/DemoData.cs
public record PackageCostLine(string Season, string RateBasis, string Supplier, string CostGroup, string Description,
    int Qty, string Unit, string Pricing, decimal Rate, decimal Total);
```

### Rate card

```razor
@using Fx.ControlKit.Grid

<div class="catalog">
<GridControl TValue="RateCardLine"
             DataSource="@_rateCard"
             AllowSelection="true"
             AllowSorting="true"
             AllowFiltering="true"
             AllowGrouping="true"
             AllowResizing="true"
             AllowColumnReorder="true"
             EnableHover="true"
             ShowSearchBar="true"
             Height="520px"
             GroupColumns="@_groupColumns"
             AggregateRows="_aggregates">
    <GridColumnsBase>
        <GridColumn Field="@nameof(RateCardLine.Code)"        HeaderText="Code"        Width="100px" />
        <GridColumn Field="@nameof(RateCardLine.Description)" HeaderText="Description" Width="240px" />
        <GridColumn Field="@nameof(RateCardLine.Supplier)"    HeaderText="Supplier"    Width="200px" />
        <GridColumn Field="@nameof(RateCardLine.Destination)" HeaderText="Destination" Width="130px" />
        <GridColumn Field="@nameof(RateCardLine.Category)"    HeaderText="Category"    Width="140px" />
        <GridColumn Field="@nameof(RateCardLine.Unit)"        HeaderText="Unit"        Width="80px" />
        <GridColumn Field="@nameof(RateCardLine.Rate)"        HeaderText="Rate"        Width="110px"
                    Type="ColumnType.Number" Format="C2" TextAlign="TextAlign.Right" />
        <GridColumn Field="@nameof(RateCardLine.Bookable)"    HeaderText="Bookable"    Width="90px"
                    Type="ColumnType.Boolean" TextAlign="TextAlign.Center" />
    </GridColumnsBase>
</GridControl>
</div>
```

```csharp
private List<RateCardLine> _rateCard = DemoData.GenerateRateCard();

private List<string> _groupColumns = new() { nameof(RateCardLine.Category) };

private List<AggregateRow> _aggregates = new()
{
    new AggregateRow
    {
        ShowInGroupCaption = true,
        ShowInGroupFooter = true,
        Columns = new()
        {
            new AggregateColumn { Field = nameof(RateCardLine.Rate), Type = AggregateType.Average, Format = "C2",
                GroupCaptionTemplate = "avg {value}", GroupFooterTemplate = "Avg {value}" },
            new AggregateColumn { Field = nameof(RateCardLine.Rate), Type = AggregateType.Count,
                GroupCaptionTemplate = "({value} lines)", GroupFooterTemplate = "{value} lines" },
        }
    }
};

// Data/DemoData.cs
public record RateCardLine(string Code, string Description, string Supplier, string Destination,
    string Category, string Unit, decimal Rate, bool Bookable);
```

