Course contentsShow
← C#
Lesson 1408 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Implementing Searchable DataGrids

Develop high-performance data grids with virtualization to handle massive datasets.

In this lesson, you will learn how to implement high-performance, searchable data grids in Blazor by utilizing UI virtualization to handle massive datasets without compromising browser responsiveness.

The Challenge of Large Datasets

When displaying thousands of rows in a standard HTML <table>, the browser’s DOM tree becomes bloated, leading to sluggish scrolling and high memory consumption. By implementing Virtualization, we instruct the browser to only render the rows currently visible in the user's viewport. As the user scrolls, components are recycled dynamically.

Implementing Searchable Virtualization

To make this searchable, we pair the Virtualize component with a filtered data source. Instead of filtering the entire collection in memory (which can be expensive), we calculate the subset of data based on the search input and pass it to the ItemsProvider delegate.

<input @oninput="HandleSearch" placeholder="Search records..." />

<div style="height:500px; overflow-y:scroll;">
    <Virtualize ItemsProvider="LoadData" Context="item" ItemSize="50">
        <ItemContent>
            <div class="row">@item.Name</div>
        </ItemContent>
    </Virtualize>
</div>

@code {
    private string? searchTerm;
    private List<MyData> allData = ...; // Imagine 100,000+ items

    private async ValueTask<ItemsProviderResult<MyData>> LoadData(ItemsProviderRequest request)
    {
        var filtered = allData.Where(x => x.Name.Contains(searchTerm ?? ""));
        var items = filtered.Skip(request.StartIndex).Take(request.Count).ToList();
        return new ItemsProviderResult<MyData>(items, filtered.Count());
    }

    private void HandleSearch(ChangeEventArgs e)
    {
        searchTerm = e.Value?.ToString();
        // Trigger re-render to refresh the Virtualize component
    }
}

Why this approach works

  1. Efficiency: The ItemsProvider allows the grid to fetch only the exact chunk of data needed for the current scroll position, preventing the loading of the full dataset into the DOM.
  2. Responsiveness: By moving the filtering logic into the ItemsProvider delegate, we ensure that searching triggers a targeted update rather than a full page re-render.
  3. Smooth UX: The ItemSize parameter helps the virtualizer calculate the scrollbar size accurately, ensuring users can "jump" through massive lists with fluid motion.

Key Takeaway: By combining the Virtualize component with an ItemsProvider delegate, you decouple the DOM size from the dataset size, allowing your grid to remain lightning-fast regardless of how many records are searched.