# Blazor Master-Detail Grid

URL: https://flexcoreui.com/demo/grid/master-detail  
Section: Data Grid  
Controls: GridControl, GridColumn, GridControlEvents  
Keywords: master-detail, hierarchy grid, detail template, row detail, drill-down

Master-detail in Blazor: pick one of 233 countries to list its airports, or open a row under a product to see its stock by warehouse.

## Documentation

### Grid

| Name | Type | Default | Description |
|---|---|---|---|
| AllowSelection | bool | true | False makes the grid cursor-only: clicks and keys still move the active cell, editing and the click events still work, but nothing is ever selected and no selection event fires. |
| AutoSelectFirstRow | bool | false | Selects the first visible row when a selectable grid first receives rows, and again after a sort changes the order. Raises RowSelected but not RowSelecting. Skipped in Cell mode and with CheckboxOnly. |
| InitialSelectedRowIndex | int? | null | Displayed-row index to select before the first paint, for pickers that already know their value. Applied again when the data source or the index changes. |
| HighlightSelectedRows | bool | true | False keeps the selection and its events but does not paint the selected rows. |
| SelectionSettingsRef | SelectionSettings? | null | The settings object below. Null behaves as single row selection. |
| EventsRef | GridControlEvents<TValue>? | null | The object that holds the callbacks; the grid has no separate parameters for the selection events. |

### Settings

| Name | Type | Default | Description |
|---|---|---|---|
| Type | SelectionType | SelectionType.Single | Single keeps one row; Ctrl or Shift with a click or an arrow still extends it unless ModifierKeysExtendSelection is off. Multiple: a plain click still collapses to the clicked row; Ctrl toggles a row, Shift selects the visible range from the last selected row. |
| Mode | SelectionMode | SelectionMode.Row | Row or Cell. In Cell mode the selected set is cells, SelectionChanged counts cells, and AutoSelectFirstRow is skipped. |
| ShowCheckboxes | bool | false | Adds the selection checkbox column while ordinary clicks still select. |
| CheckboxOnly | bool | false | Only the checkboxes change the selection; a click on a cell does not, and AutoSelectFirstRow is skipped. |
| ModifierKeysExtendSelection | bool | true | With Single, Ctrl or Shift plus a click or Shift plus an arrow add rows. False keeps exactly one row: a modifier click selects the clicked row alone. Ignored for Multiple and for Cell mode. |
| MultiSelectBehavior | GridMultiSelectBehavior | GridMultiSelectBehavior.FullMultiSelect | With BatchEditBehavior = MultiRow and several rows selected, FullMultiSelect keeps the selection when a plain click lands on an editable, template or command cell inside it, so a bulk edit stays armed; VBMultiSelect lets that click collapse to the clicked row. Ctrl, Shift and drag build multi-row selections in both. |
| EnableToggle | bool | true | Declared, but GridControl never reads it. |
| PersistSelection | bool | false | Declared, but GridControl never reads it. |

### Events

| Name | Type | Description |
|---|---|---|
| RowSelecting | RowSelectEventArgs<TValue> | Before a row is selected by mouse, keyboard or checkbox toggle. Set Cancel to refuse. Not raised by AutoSelectFirstRow, type-ahead moves or the selection methods. |
| RowSelected | RowSelectEventArgs<TValue> | After a row is selected by mouse, keyboard, checkbox toggle, type-ahead search or AutoSelectFirstRow. Not raised during drag-select or by the selection methods. |
| SelectionChanged | int | After any change to the selected set: click, drag-select, Select All, Clear, the selection methods. The payload is the selected count, rows or cells by Mode. |
| SelectionChangedDetailed | GridSelectionChangedArgs | Same timing, with Count and Source: Pointer, MouseDrag, Keyboard, Programmatic or Unknown. |
| RowDeselecting / RowDeselected | RowSelectEventArgs<TValue> | Declared, but GridControl never raises them. TreeGridControl raises RowDeselected. |

### Args

| Name | Type | Default | Description |
|---|---|---|---|
| Data | TValue? | null | The row. |
| RowIndex | int | 0 | The row's index in the grid's current display order. |
| Cancel | bool | false | Set in RowSelecting to keep the current selection. Ignored by RowSelected. |

### Methods

| Name | Type | Description |
|---|---|---|
| GetSelectedRecords() | IEnumerable<TValue> | The selected rows, in selection order. |
| GetSelectedRecordsAsync() | Task<List<TValue>> | The same as a list. |
| SelectRow(int rowIndex) | void | Selects the displayed row at that index; with Single it replaces the selection, otherwise it adds. |
| SelectRowIndexAsync(int rowIndex) | Task | SelectRow as a task. |
| SelectAndRevealRowAsync(TValue item, bool clearExistingSelection = false) | Task | Selects the row and scrolls it into view when it is off-screen, in one paint. |
| ClearSelection() | void | Clears rows and cells. |
| ClearSelectionAsync() | Task | ClearSelection as a task. |

### Detail

| Name | Type | Default | Description |
|---|---|---|---|
| DetailTemplate | RenderFragment<TValue>? | null | Content for a full-width row under a data row while that row is open; context is the row. With a template set the grid renders every row of the current page rather than a scrolling window, and a flat ItemsProvider throws at start-up. |
| ExpandMode | GridExpandMode | GridExpandMode.Multiple | Multiple keeps any number of rows open. Single closes the open row when another opens, without raising RowCollapse for it. |
| ShowExpandColumn | bool | true | The 36 px arrow column at the left of every row. False leaves opening and closing to the methods. |
| ShowExpandAll | bool | false | An arrow in the header of that column that opens or closes every row of the page; shown only with Multiple. |

### Detail events

| Name | Type | Description |
|---|---|---|
| RowExpand | TValue | After a row opens by its arrow, ExpandRow or ToggleRowExpand. Not raised by ExpandAll or the header arrow. |
| RowCollapse | TValue | After a row closes by its arrow, CollapseRow or ToggleRowExpand. Not raised by CollapseAll, the header arrow, or Single mode replacing the open row. |

### Detail methods

| Name | Type | Description |
|---|---|---|
| ExpandRow(TValue item) | Task | Opens the row; in Single mode the open row closes first. |
| CollapseRow(TValue item) | Task | Closes the row. |
| ToggleRowExpand(TValue item) | Task | One or the other, by the row's state. |
| ExpandAll() / CollapseAll() / ToggleExpandAll() | void | Every row of the current page, without the row events. |
| IsRowExpanded(TValue item) | bool | Whether the row is open. |
| AllRowsExpanded | bool | Property: every row of the current page is open. |

## Examples

### Countries

```razor
@using Fx.ControlKit.Grid

<div class="pair">
    <div>
        <p class="pane-title">Countries</p>
        <GridControl TValue="CountryRow"
                     DataSource="@_countries"
                     Height="340px"
                     AllowSelection="true"
                     AllowSorting="true"
                     ShowSearchBar="true"
                     AutoSelectFirstRow="true"
                     SelectionSettingsRef="@_singleRow"
                     EventsRef="@_countryEvents">
            <GridColumnsBase>
                <GridColumn Field="@nameof(CountryRow.Name)" HeaderText="Country" Width="180px" />
                <GridColumn Field="@nameof(CountryRow.Code)" HeaderText="ISO" Width="60px" />
                <GridColumn Field="@nameof(CountryRow.Airports)" HeaderText="Airports" Width="80px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="#,##0" />
            </GridColumnsBase>
        </GridControl>
    </div>
    <div>
        <p class="pane-title">Airports in @(_country?.Name ?? "…")</p>
        <GridControl TValue="Airport"
                     DataSource="@_countryAirports"
                     Height="340px"
                     AllowSorting="true"
                     ShowRowCountInFooter="true">
            <GridColumnsBase>
                <GridColumn Field="@nameof(Airport.Code)" HeaderText="Code" Width="60px" />
                <GridColumn Field="@nameof(Airport.Name)" HeaderText="Airport" Width="220px" />
                <GridColumn Field="@nameof(Airport.City)" HeaderText="City" Width="130px" />
                <GridColumn Field="@nameof(Airport.Type)" HeaderText="Type" Width="75px" />
                <GridColumn Field="@nameof(Airport.Runways)" HeaderText="Runways" Width="75px" Type="ColumnType.Number" TextAlign="TextAlign.Right" />
            </GridColumnsBase>
        </GridControl>
    </div>
</div>
<p class="result">@_countryAirports.Count.ToString("#,##0") airports in @(_country?.Name ?? "no country"), @_countryAirports.Count(a => a.Type == "Large") of them large.</p>
```

```csharp
// Countries: one row per ISO code, most airports first; the airports are the detail rows.
private readonly List<CountryRow> _countries = AirportData.Airports
    .GroupBy(a => (a.CountryCode, a.Country))
    .Select(g => new CountryRow(g.Key.CountryCode, g.Key.Country, g.Count()))
    .OrderByDescending(c => c.Airports).ThenBy(c => c.Name)
    .ToList();
private List<Airport> _countryAirports = [];
private CountryRow? _country;

private readonly SelectionSettings _singleRow = new() { Mode = SelectionMode.Row, Type = SelectionType.Single };
private readonly GridControlEvents<CountryRow> _countryEvents = new();

protected override void OnInitialized()
{
    _countryEvents.RowSelected = EventCallback.Factory.Create<RowSelectEventArgs<CountryRow>>(this, args => Show(args.Data));
    Show(_countries.FirstOrDefault());
}

private void Show(CountryRow? country)
{
    _country = country;
    _countryAirports = country is null ? [] : AirportData.Airports.Where(a => a.CountryCode == country.Code).ToList();
}

private sealed record CountryRow(string Code, string Name, int Airports);
```

### Warehouses

```razor
@using Fx.ControlKit
@using Fx.ControlKit.Grid

<ButtonGroupControl Items="CategoryItems" Values="@(new[] { _category })" ValuesChanged="Filter" Selection="ChoiceSelectionMode.Single" AriaLabel="Category" />

<GridControl @ref="_grid"
             TValue="InventoryProduct"
             DataSource="@Shown"
             Height="400px"
             AllowSorting="true"
             ShowRowCountInFooter="true"
             ExpandMode="GridExpandMode.Single"
             RowExpand="Opened"
             RowCollapse="Closed">
    <ChildContent>
        <GridColumnsBase>
            <GridColumn Field="@nameof(InventoryProduct.SKU)" HeaderText="SKU" Width="100px" />
            <GridColumn Field="@nameof(InventoryProduct.ProductName)" HeaderText="Product" Width="220px" />
            <GridColumn Field="@nameof(InventoryProduct.Category)" HeaderText="Category" Width="120px" />
            <GridColumn Field="@nameof(InventoryProduct.TotalOnHand)" HeaderText="On hand" Width="90px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="#,##0" />
            <GridColumn Field="@nameof(InventoryProduct.TotalReserved)" HeaderText="Reserved" Width="90px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="#,##0" />
            <GridColumn Field="@nameof(InventoryProduct.AvailableStock)" HeaderText="Available" Width="90px" Type="ColumnType.Number" TextAlign="TextAlign.Right">
                <Template>
                    @{ var p = (InventoryProduct)context; }
                    <span class="@(p.AvailableStock <= 0 ? "out" : p.AvailableStock <= p.ReorderPoint ? "low" : "")">@p.AvailableStock.ToString("#,##0")</span>
                </Template>
            </GridColumn>
            <GridColumn Field="@nameof(InventoryProduct.ReorderPoint)" HeaderText="Reorder at" Width="90px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="#,##0" />
            <GridColumn Field="@nameof(InventoryProduct.InventoryValuation)" HeaderText="Valuation" Width="110px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="C0" />
        </GridColumnsBase>
    </ChildContent>
    <DetailTemplate Context="product">
        <div class="detail">
            <div class="detail-bar">
                <span>@product.WarehouseDetails.Count warehouses hold @product.TotalOnHand.ToString("#,##0") on hand, @product.TotalReserved.ToString("#,##0") reserved, @product.WarehouseDetails.Sum(w => w.IncomingShipmentQty).ToString("#,##0") incoming.</span>
                <ButtonControl CssClass="btn-sm" OnClick="() => Receive(product)">Receive next shipment</ButtonControl>
                <ButtonControl CssClass="btn-sm" OnClick="() => Reserve(product)">Reserve 10</ButtonControl>
            </div>
            <GridControl TValue="WarehouseStock" DataSource="@product.WarehouseDetails" AllowSorting="true">
                <GridColumnsBase>
                    <GridColumn Field="@nameof(WarehouseStock.WarehouseCode)" HeaderText="Code" Width="80px" />
                    <GridColumn Field="@nameof(WarehouseStock.WarehouseName)" HeaderText="Warehouse" Width="160px" />
                    <GridColumn Field="@nameof(WarehouseStock.LocationBin)" HeaderText="Bin" Width="120px" />
                    <GridColumn Field="@nameof(WarehouseStock.QuantityOnHand)" HeaderText="On hand" Width="85px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="#,##0" />
                    <GridColumn Field="@nameof(WarehouseStock.ReservedQuantity)" HeaderText="Reserved" Width="85px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="#,##0" />
                    <GridColumn Field="@nameof(WarehouseStock.AvailableQuantity)" HeaderText="Available" Width="85px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="#,##0" />
                    <GridColumn Field="@nameof(WarehouseStock.IncomingShipmentQty)" HeaderText="Incoming" Width="85px" Type="ColumnType.Number" TextAlign="TextAlign.Right" Format="#,##0" />
                    <GridColumn Field="@nameof(WarehouseStock.NextDeliveryDate)" HeaderText="Next delivery" Width="105px" Type="ColumnType.Date" Format="yyyy-MM-dd" />
                    <GridColumn Field="@nameof(WarehouseStock.BatchLotNumber)" HeaderText="Lot" Width="120px" />
                </GridColumnsBase>
            </GridControl>
        </div>
    </DetailTemplate>
</GridControl>
<p class="result">@Shown.Count products worth @Shown.Sum(p => p.InventoryValuation).ToString("C0") on hand@(_open is null ? "; no detail open." : $"; {_open.SKU} open.")</p>
```

```csharp
private GridControl<InventoryProduct>? _grid;

private readonly List<InventoryProduct> _products = BenchDataStore.GetInventoryProducts();

private List<InventoryProduct>? _shown;

private List<InventoryProduct> Shown => _shown ??= _products.ToList();

private SelectionItem[]? _categoryItems;

private SelectionItem[] CategoryItems => _categoryItems ??= [new("All", "All"), .. _products.Select(p => p.Category).Distinct().Select(c => new SelectionItem(c, c))];

private string _category = "All";

private InventoryProduct? _open;

private async Task Filter(IReadOnlyList<string> values)
{
    if (values.Count == 0) return;
    _category = values[0];
    _shown = _category == "All" ? _products.ToList() : _products.Where(p => p.Category == _category).ToList();
    if (_open is not null && !_shown.Contains(_open) && _grid is not null) await _grid.CollapseRow(_open);
}

private void Opened(InventoryProduct product) => _open = product;

private void Closed(InventoryProduct product)
{
    if (ReferenceEquals(_open, product)) _open = null;
}

private static void Receive(InventoryProduct product)
{
    var stock = product.WarehouseDetails.MaxBy(w => w.IncomingShipmentQty);
    if (stock is null || stock.IncomingShipmentQty == 0) return;
    stock.QuantityOnHand += stock.IncomingShipmentQty;
    product.TotalOnHand += stock.IncomingShipmentQty;
    stock.IncomingShipmentQty = 0;
}

private static void Reserve(InventoryProduct product)
{
    var stock = product.WarehouseDetails.FirstOrDefault(w => w.AvailableQuantity >= 10);
    if (stock is null) return;
    stock.ReservedQuantity += 10;
    product.TotalReserved += 10;
}

// Data/ScenarioModels.cs
public sealed class InventoryProduct
{
    public string SKU { get; set; } = "";
    public string ProductName { get; set; } = "";
    public string Category { get; set; } = "";
    public int TotalOnHand { get; set; }
    public int TotalReserved { get; set; }
    public int AvailableStock => TotalOnHand - TotalReserved;
    public int ReorderPoint { get; set; }
    public decimal UnitCost { get; set; }
    public decimal InventoryValuation => TotalOnHand * UnitCost;
    public string StockStatus => AvailableStock <= 0 ? "Out of Stock" : AvailableStock <= ReorderPoint ? "Low Stock" : "In Stock";
    public List<WarehouseStock> WarehouseDetails { get; set; } = new();
}

// Data/ScenarioModels.cs
public sealed class WarehouseStock
{
    public string WarehouseCode { get; set; } = "";
    public string WarehouseName { get; set; } = "";
    public string LocationBin { get; set; } = "";
    public int QuantityOnHand { get; set; }
    public int ReservedQuantity { get; set; }
    public int AvailableQuantity => QuantityOnHand - ReservedQuantity;
    public int IncomingShipmentQty { get; set; }
    public DateTime NextDeliveryDate { get; set; }
    public string BatchLotNumber { get; set; } = "";
}
```

