# On-Demand Data Loading in a Blazor Grid

URL: https://flexcoreui.com/demo/grid/provider-enterprise  
Section: Data Grid  
Controls: GridControl, GridColumn, GridItemsRequest  
Keywords: items provider, server-side paging, remote data, lazy loading, on-demand loading

Load only what users open: an ItemsProvider serves a Blazor grid's rows, groups, totals and export pages on demand, here 12,000 orders.

## Documentation

### Request

| Name | Type | Default | Description |
|---|---|---|---|
| StartIndex | int |  | Zero-based index in the complete filtered and sorted result. |
| Count | int |  | Maximum number of rows requested. |
| QueryVersion | long |  | Increases with every query or context change; results from an older version must not be applied. |
| IncludeTotalCount | bool |  | True when the grid needs an authoritative total for this query generation, so a provider can skip a repeated count. |
| Query | GridQueryDescriptor |  | The current sorts, filters, search text and grouping; the next table. |
| ContextKey | object? |  | Opaque host value for the surrounding dataset, passed through uninterpreted. |
| CancellationToken | CancellationToken |  | Canceled when a newer range or query supersedes the request. |
| Purpose | GridItemsRequestPurpose | Rows | Why the range is requested: Rows, Groups, GroupChildren, GroupItems, Export or FilterValues. |
| GroupRequest | GridProviderGroupRequest? | null | Parent group for lazy grouping requests; null for row windows, root groups and exports. |
| FilterField | string? | null | Field whose distinct values are requested for a FilterValues request; null otherwise. |

### Query

| Name | Type | Default | Description |
|---|---|---|---|
| Sorts | IReadOnlyList<GridSortDescriptor> |  | Ordered sort terms; earlier entries rank higher. |
| Filters | IReadOnlyList<GridFilterDescriptor> |  | Column filters. |
| SearchText | string? |  | Text from the search box, or null. |
| SearchFields | IReadOnlyList<string> |  | Fields the search covers. |
| ExpressionFilterText | string? | null | Expression typed in the detailed-search box; a provider that does not understand it may ignore it. |
| Groups | IReadOnlyList<GridGroupQueryDescriptor> | empty | Active grouping terms, outermost first. |
| Aggregates | IReadOnlyList<GridAggregateQueryDescriptor> | empty | Aggregates the configured aggregate rows ask for. |
| CaseSensitive | bool | false | True when text comparisons on the provider side must be case-sensitive. |

### Result

| Name | Type | Default | Description |
|---|---|---|---|
| Items | IReadOnlyList<TValue> |  | The rows of this range. |
| TotalCount | int |  | Rows in the complete filtered result. |
| Groups | IReadOnlyList<GridProviderGroup<TValue>> | empty | Groups for a Groups or GroupChildren request; row providers leave it empty. |
| Aggregates | IReadOnlyList<GridAggregateResult> | empty | Aggregate values for the whole current query, so totals never come from the loaded window alone. |
| ResultSetCount | int? | null | Entries in this result set; when omitted the grid uses TotalCount for root rows and group metadata for child ranges. |
| HasMore | bool | false | Continuation hint for providers whose result size is costly to count; the grid also infers it from known counts. |
| FilterValues | IReadOnlyList<GridProviderFilterValue> | empty | Distinct values for a FilterValues request. |

### Provider

| Name | Type | Default | Description |
|---|---|---|---|
| ItemsProvider | GridItemsProvider<TValue>? | null | Delegate the grid calls for every range it needs. Set, it replaces DataSource and the local pipeline. |
| ItemsProviderContextKey | object? | null | Opaque host value sent with every request. Changing it starts a new query generation and reloads from the first row. |
| ItemKeySelector | Func<TValue, object?>? | null | Stable identity used as the row key when provider calls return new objects for the same database row. |
| ItemsProviderCacheSize | int | 4 | Completed ranges the grid keeps in memory; clamped to a small bounded range. |
| EnableProviderFilterValueRequests | bool | false | Sends FilterValues requests, with FilterField set, so the checklist filter can list a column's distinct values from the provider. |
| ProviderFilterValueRequestSize | int | 1000 | Most distinct values asked for in one checklist menu. |
| EnableProviderGrouping | bool | false | Lets the provider serve the group tree when group descriptors are active. Off, so existing flat providers keep their contract. |
| ProviderGroupPageSize | int | 100 | Most groups requested per lazy group page. |
| ProviderGroupItemPageSize | int | 250 | Most leaf rows requested per lazy group page. |
| ProviderGroupsInitiallyCollapsed | bool | true | New provider groups arrive collapsed, so enabling remote grouping never loads the whole hierarchy at once. |
| ExportAllProviderItems | bool | false | Exports page through the complete current query with Export requests instead of the loaded window only. Local DataSource exports are unaffected. |
| ProviderExportPageSize | int | 1000 | Rows requested per export page. |
| ProviderExportProgressChanged | EventCallback<GridProviderExportProgress> |  | After every received export page, and on completion or cancellation. |

### Group

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string |  | Field the group is keyed on. |
| Key | object? |  | The group's value of that field. |
| DisplayText | string? |  | Caption text; null shows the key. |
| Count | int |  | Rows in the group, counted through every level below it. |
| GroupPath | string? | null | Stable path; when empty the grid derives one from the parent path, field and key. |
| HasChildren | bool | true | True when expanding can reveal sub-groups or rows; false draws a leaf group. |
| Groups | IReadOnlyList<GridProviderGroup<TValue>> | empty | Child groups supplied with the parent, so no GroupChildren request is needed for them. |
| Items | IReadOnlyList<TValue> | empty | Leaf rows supplied with the group, so no GroupItems request is needed for them. |
| Aggregates | IReadOnlyList<GridAggregateResult> | empty | Aggregate values across every row in the group, for its caption and footer. |
| ChildCount | int? | null | Direct children at the next level, as distinct from the recursive Count. |

### Group request

| Name | Type | Description |
|---|---|---|
| Level | int | Zero-based grouping level of the parent whose children or rows are wanted. |
| ParentKeys | IReadOnlyList<GridProviderGroupKey> | Field and value of each ancestor, from the root group down to the parent. |
| ParentPath | string | The parent's GroupPath. |

### Group key

| Name | Type | Description |
|---|---|---|
| Field | string | Field of one ancestor group. |
| Value | object? | Its key value. |

### Progress

| Name | Type | Default | Description |
|---|---|---|---|
| ExportedRows | int |  | Rows received so far. |
| TotalRows | int? |  | Rows in the whole query when the provider reported a total; null otherwise. |
| IsCompleted | bool |  | True on the final notification. |
| IsCanceled | bool | false | True when the export stopped before the end. |

### Aggregate

| Name | Type | Description |
|---|---|---|
| Field | string | Field the value was computed over. |
| Type | AggregateType | Sum, Average, Count, Min or Max. |
| Value | object? | The computed value, boxed. |

## Examples

### Search

```razor
@using Fx.ControlKit.Grid

<GridControl TValue="RateCardItem"
             ItemsProvider="LoadItemsAsync"
             Height="380px"
             AllowSorting="true"
             AllowFiltering="false"
             AllowSelection="true"
             AllowResizing="true"
             ShowSearchBar="true"
             ShowRowCountInFooter="true">
    <GridColumnsBase>
        <GridColumn Field="@nameof(RateCardItem.Code)" HeaderText="Code" Width="95px" />
        <GridColumn Field="@nameof(RateCardItem.Description)" HeaderText="Description" Width="215px" />
        <GridColumn Field="@nameof(RateCardItem.Supplier)" HeaderText="Supplier" Width="185px" />
        <GridColumn Field="@nameof(RateCardItem.Region)" HeaderText="Region" Width="115px" />
        <GridColumn Field="@nameof(RateCardItem.Destination)" HeaderText="Destination" Width="120px" />
        <GridColumn Field="@nameof(RateCardItem.Category)" HeaderText="Category" Width="115px" />
        <GridColumn Field="@nameof(RateCardItem.Unit)" HeaderText="Unit" Width="65px" TextAlign="TextAlign.Center" />
        <GridColumn Field="@nameof(RateCardItem.Rate)" HeaderText="Rate" Width="100px" Type="ColumnType.Number" Format="C2" TextAlign="TextAlign.Right" />
    </GridColumnsBase>
</GridControl>
<p class="result">@_flatLast</p>
```

```csharp
// Flat provider (moved here from the On-demand items provider page, 2026-10-20): the rate card is an in-memory list synthesized
// for each visitor and stands in for a database; only the requested range leaves this method.
private int _flatRequests;

private string _flatLast = "Waiting for the first request…";

private async ValueTask<GridItemsResult<RateCardItem>> LoadItemsAsync(GridItemsRequest request)
{
    await Task.Delay(25, request.CancellationToken);
    IEnumerable<RateCardItem> rows = BenchData.RateCard;
    var text = request.Query.SearchText;
    if (!string.IsNullOrWhiteSpace(text))
    {
        var comparison = request.Query.CaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
        rows = rows.Where(r => r.Code.Contains(text, comparison)
                            || r.Description.Contains(text, comparison)
                            || r.Supplier.Contains(text, comparison));
    }
    var matched = SortItems(rows, request.Query.Sorts).ToList();
    var page = matched.Skip(request.StartIndex).Take(request.Count).ToList();
    _flatLast = $"Request {++_flatRequests}: {request.Purpose}, start {request.StartIndex:N0}, count {request.Count:N0}; "
              + $"{page.Count} of {matched.Count:N0} matching rows returned"
              + (string.IsNullOrWhiteSpace(text) ? "." : $" for \"{text}\".");
    await InvokeAsync(StateHasChanged);
    return new GridItemsResult<RateCardItem>(page, matched.Count);
}

private static IEnumerable<RateCardItem> SortItems(IEnumerable<RateCardItem> rows, IReadOnlyList<GridSortDescriptor> sorts)
{
    IOrderedEnumerable<RateCardItem>? ordered = null;
    foreach (var sort in sorts)
    {
        var property = typeof(RateCardItem).GetProperty(sort.Field);
        if (property is null) continue;
        Func<RateCardItem, object?> key = r => property.GetValue(r);
        ordered = ordered is null
            ? sort.Direction == SortDirection.Descending ? rows.OrderByDescending(key) : rows.OrderBy(key)
            : sort.Direction == SortDirection.Descending ? ordered.ThenByDescending(key) : ordered.ThenBy(key);
    }
    return ordered ?? rows;
}
```

### Orders

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

<div class="orders">
<GridControl @ref="_grid"
             TValue="ProviderOrder"
             ItemsProvider="LoadOrdersAsync"
             ItemKeySelector="@(row => row.Id)"
             Height="520px"
             AllowGrouping="true"
             GroupColumns="@_groups"
             EnableProviderGrouping="true"
             ProviderGroupsInitiallyCollapsed="true"
             ProviderGroupPageSize="2"
             ProviderGroupItemPageSize="75"
             ShowGroupCount="true"
             AllowSorting="true"
             ShowSearchBar="true"
             AllowResizing="true"
             ProviderExportPageSize="400"
             ProviderExportProgressChanged="OnExportProgress"
             ShowRowCountInFooter="true"
             AggregateRows="@_aggregates">
    <GridColumnsBase>
        <GridColumn Field="@nameof(ProviderOrder.Id)" HeaderText="Order" Width="90px" Type="ColumnType.Number" />
        <GridColumn Field="@nameof(ProviderOrder.Region)" HeaderText="Region" Width="120px" />
        <GridColumn Field="@nameof(ProviderOrder.Category)" HeaderText="Category" Width="140px" />
        <GridColumn Field="@nameof(ProviderOrder.Customer)" HeaderText="Customer" Width="220px" />
        <GridColumn Field="@nameof(ProviderOrder.OrderDate)" HeaderText="Date" Width="110px" Type="ColumnType.Date" Format="d" />
        <GridColumn Field="@nameof(ProviderOrder.Quantity)" HeaderText="Qty" Width="80px" Type="ColumnType.Number" TextAlign="TextAlign.Right" />
        <GridColumn Field="@nameof(ProviderOrder.Amount)" HeaderText="Amount" Width="120px" Type="ColumnType.Number" Format="C2" TextAlign="TextAlign.Right" />
    </GridColumnsBase>
</GridControl>
</div>
<p class="result">@_lastRequest @ExportText</p>
```

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

private readonly List<ProviderOrder> _orders = BuildOrders();

private readonly List<string> _groups =
[
    nameof(ProviderOrder.Region),
    nameof(ProviderOrder.Category)
];

private GridProviderExportProgress? _exportProgress;

private int _requestCount;

private string _lastRequest = "Waiting for the first request…";

private readonly List<AggregateRow> _aggregates =
[
    new AggregateRow
    {
        ShowInGroupCaption = true,
        ShowInFooter = true,
        Columns =
        [
            new AggregateColumn
            {
                Field = nameof(ProviderOrder.Amount),
                Type = AggregateType.Sum,
                Format = "C2",
                GroupCaptionTemplate = "sum {value}",
                FooterTemplate = "Total {value}"
            }
        ]
    }
];

private string ExportText => _exportProgress is not { } p ? "" :
    $"· Export: {p.ExportedRows:N0}" + (p.TotalRows is { } total ? $" of {total:N0}" : "")
    + (p.IsCanceled ? " (canceled)" : p.IsCompleted ? " (complete)" : "");

private async ValueTask<GridItemsResult<ProviderOrder>> LoadOrdersAsync(GridItemsRequest request)
{
    await Task.Delay(request.Purpose == GridItemsRequestPurpose.Export ? 60 : 90, request.CancellationToken);
    var filtered = ApplyQuery(_orders, request.Query).ToList();
    var scoped = ApplyGroupKeys(filtered, request.GroupRequest?.ParentKeys).ToList();
    var totals = request.GroupRequest is null ? filtered : scoped;   // the grid stores a child page's aggregates on the parent group
    var under = request.GroupRequest is { } parent
        ? " under " + string.Join(" / ", parent.ParentKeys.Select(key => key.Value))
        : "";
    _lastRequest = $"Request {++_requestCount}: {request.Purpose}{under}, start {request.StartIndex:N0}, count {request.Count:N0}.";
    await InvokeAsync(StateHasChanged);

    if (request.Purpose is GridItemsRequestPurpose.Groups or GridItemsRequestPurpose.GroupChildren)
    {
        var level = request.Purpose == GridItemsRequestPurpose.Groups
            ? 0
            : request.GroupRequest!.Level + 1;
        var descriptor = request.Query.Groups[level];
        var groups = scoped
            .GroupBy(row => GetFieldValue(row, descriptor.Field))
            .Select(group => new
            {
                Key = group.Key,
                Rows = group.ToList()
            });
        groups = descriptor.Direction == SortDirection.Descending
            ? groups.OrderByDescending(group => Convert.ToString(group.Key, CultureInfo.CurrentCulture))
            : groups.OrderBy(group => Convert.ToString(group.Key, CultureInfo.CurrentCulture));
        var groupList = groups.ToList();
        var page = groupList
            .Skip(request.StartIndex)
            .Take(request.Count)
            .Select(group => new GridProviderGroup<ProviderOrder>(
                descriptor.Field,
                group.Key,
                Convert.ToString(group.Key, CultureInfo.CurrentCulture),
                group.Rows.Count)
            {
                HasChildren = group.Rows.Count > 0,
                Aggregates = BuildAggregates(group.Rows, request.Query.Aggregates)
            })
            .ToList();

        return new GridItemsResult<ProviderOrder>(Array.Empty<ProviderOrder>(), filtered.Count)
        {
            Groups = page,
            ResultSetCount = groupList.Count,
            HasMore = request.StartIndex + page.Count < groupList.Count,
            Aggregates = BuildAggregates(totals, request.Query.Aggregates)
        };
    }

    var sorted = ApplySorts(scoped, request.Query.Sorts).ToList();
    var items = sorted.Skip(request.StartIndex).Take(request.Count).ToList();
    return new GridItemsResult<ProviderOrder>(items, filtered.Count)
    {
        ResultSetCount = sorted.Count,
        HasMore = request.StartIndex + items.Count < sorted.Count,
        Aggregates = BuildAggregates(totals, request.Query.Aggregates)
    };
}

private static IEnumerable<ProviderOrder> ApplyQuery(
    IEnumerable<ProviderOrder> source,
    GridQueryDescriptor query)
{
    var rows = source;
    if (!string.IsNullOrWhiteSpace(query.SearchText))
    {
        var comparison = query.CaseSensitive
            ? StringComparison.CurrentCulture
            : StringComparison.CurrentCultureIgnoreCase;
        rows = rows.Where(row =>
            row.Customer.Contains(query.SearchText, comparison)
            || row.Region.Contains(query.SearchText, comparison)
            || row.Category.Contains(query.SearchText, comparison));
    }
    return rows;
}

private static IEnumerable<ProviderOrder> ApplyGroupKeys(
    IEnumerable<ProviderOrder> source,
    IReadOnlyList<GridProviderGroupKey>? keys)
{
    if (keys is null)
        return source;
    foreach (var key in keys)
    {
        source = source.Where(row => Equals(
            Convert.ToString(GetFieldValue(row, key.Field), CultureInfo.InvariantCulture),
            Convert.ToString(key.Value, CultureInfo.InvariantCulture)));
    }
    return source;
}

private static IEnumerable<ProviderOrder> ApplySorts(
    IEnumerable<ProviderOrder> source,
    IReadOnlyList<GridSortDescriptor> sorts)
{
    IOrderedEnumerable<ProviderOrder>? ordered = null;
    foreach (var sort in sorts)
    {
        Func<ProviderOrder, object?> selector = row => GetFieldValue(row, sort.Field);
        ordered = ordered is null
            ? sort.Direction == SortDirection.Descending
                ? source.OrderByDescending(selector)
                : source.OrderBy(selector)
            : sort.Direction == SortDirection.Descending
                ? ordered.ThenByDescending(selector)
                : ordered.ThenBy(selector);
    }
    return ordered ?? source.OrderBy(row => row.Id);
}

private static object? GetFieldValue(ProviderOrder row, string field) => field switch
{
    nameof(ProviderOrder.Id) => row.Id,
    nameof(ProviderOrder.Region) => row.Region,
    nameof(ProviderOrder.Category) => row.Category,
    nameof(ProviderOrder.Customer) => row.Customer,
    nameof(ProviderOrder.OrderDate) => row.OrderDate,
    nameof(ProviderOrder.Quantity) => row.Quantity,
    nameof(ProviderOrder.Amount) => row.Amount,
    _ => null
};

private static IReadOnlyList<GridAggregateResult> BuildAggregates(
    IReadOnlyCollection<ProviderOrder> rows,
    IReadOnlyList<GridAggregateQueryDescriptor> requested)
{
    return requested.Select(aggregate =>
    {
        object? value = (aggregate.Field, aggregate.Type) switch
        {
            (nameof(ProviderOrder.Amount), AggregateType.Sum) => rows.Sum(row => row.Amount),
            (nameof(ProviderOrder.Amount), AggregateType.Average) when rows.Count > 0 => rows.Average(row => row.Amount),
            (nameof(ProviderOrder.Amount), AggregateType.Min) when rows.Count > 0 => rows.Min(row => row.Amount),
            (nameof(ProviderOrder.Amount), AggregateType.Max) when rows.Count > 0 => rows.Max(row => row.Amount),
            (_, AggregateType.Count) => rows.Count,
            _ => null
        };
        return new GridAggregateResult(aggregate.Field, aggregate.Type, value);
    }).ToList();
}

private Task ExportCsvAsync() =>
    _grid?.ExportProviderQueryAsync(GridExportFormat.Csv, "orders.csv", "Orders") ?? Task.CompletedTask;

private void CancelExport() => _grid?.CancelProviderExport();

private Task OnExportProgress(GridProviderExportProgress progress)
{
    _exportProgress = progress;
    return Task.CompletedTask;
}

private static List<ProviderOrder> BuildOrders()
{
    string[] regions = ["North", "South", "East", "West"];
    string[] categories = ["Cabinets", "Electrical", "Flooring", "Hardware", "Plumbing", "Windows"];
    var rows = new List<ProviderOrder>(12_000);
    for (var id = 1; id <= 12_000; id++)
    {
        rows.Add(new ProviderOrder
        {
            Id = id,
            Region = regions[id % regions.Length],
            Category = categories[(id * 7) % categories.Length],
            Customer = $"Customer {(id * 13) % 425:D3}",
            OrderDate = new DateTime(2024, 1, 1).AddDays(id % 730),
            Quantity = 1 + id % 50,
            Amount = 25m + (id % 500) * 3.17m
        });
    }
    return rows;
}

private sealed class ProviderOrder
{
    public int Id { get; init; }
    public string Region { get; init; } = "";
    public string Category { get; init; } = "";
    public string Customer { get; init; } = "";
    public DateTime OrderDate { get; init; }
    public int Quantity { get; init; }
    public decimal Amount { get; init; }
}
```

