Creating a fully featured Excel-like grid component in a single Blazor component file with virtualization, cell navigation, editing, filtering, sorting, and smooth one-by-one row scrolling with arrow keys is quite complex. However, I can provide a comprehensive starting point that covers these features in a simplified but extensible way.
This example uses:
- Virtualization with
Virtualize component
- Keyboard navigation (arrow keys)
- Inline cell editing
- Basic sorting and filtering
- Smooth one-row scrolling on arrow down/up
You can extend this foundation as needed.
ExcelGrid.razor
@using System.Linq.Expressions
@typeparam TItem
<div tabindex="0" @onkeydown="OnKeyDown" style="outline:none; max-height:400px; overflow:auto;" @ref="GridDiv">
<input placeholder="Filter..." @bind="FilterText" @bind:event="oninput" style="margin-bottom:5px; width:100%;" />
<table class="table table-bordered table-sm" style="table-layout: fixed; width: 100%; user-select:none;">
<thead>
<tr>
@foreach (var col in Columns)
{
<th @onclick="() => SortBy(col)">
@col.Header
@if (SortColumn == col)
{
<span>@(SortDescending ? "▼" : "▲")</span>
}
</th>
}
</tr>
</thead>
<tbody>
<Virtualize Items="FilteredItems" Context="item" ItemSize="30" @ref="VirtualizeRef">
<tr class="@GetRowClass(item)" @onclick="() => SelectRow(item)" style="cursor:pointer;">
@foreach (var col in Columns)
{
<td @onclick="(e) => StartEdit(item, col)" style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;">
@if (IsEditing(item, col))
{
<input @bind="GetCellValue(item, col)" @bind:event="oninput" @onblur="EndEdit" @onkeydown="(e) => OnCellKeyDown(e, item, col)" style="width:100%; border:none; padding:0; margin:0;" />
}
else
{
@GetCellValue(item, col)
}
</td>
}
</tr>
</Virtualize>
</tbody>
</table>
</div>
@code {
[Parameter] public List<TItem> Items { get; set; } = new();
[Parameter] public List<ColumnDefinition<TItem>> Columns { get; set; } = new();
private string FilterText { get; set; } = "";
private ColumnDefinition<TItem>? SortColumn { get; set; }
private bool SortDescending { get; set; } = false;
private TItem? SelectedItem;
private (TItem item, ColumnDefinition<TItem> col)? EditingCell;
private ElementReference GridDiv;
private Virtualize<TItem>? VirtualizeRef;
private IEnumerable<TItem> FilteredItems => ApplyFilterAndSort();
private IEnumerable<TItem> ApplyFilterAndSort()
{
IEnumerable<TItem> query = Items;
if (!string.IsNullOrWhiteSpace(FilterText))
{
query = query.Where(item =>
Columns.Any(col =>
(col.GetValue(item)?.ToString() ?? "")
.Contains(FilterText, StringComparison.OrdinalIgnoreCase)));
}
if (SortColumn != null)
{
query = SortDescending
? query.OrderByDescending(item => SortColumn.GetValue(item))
: query.OrderBy(item => SortColumn.GetValue(item));
}
return query;
}
private void SortBy(ColumnDefinition<TItem> col)
{
if (SortColumn == col)
SortDescending = !SortDescending;
else
{
SortColumn = col;
SortDescending = false;
}
}
private void SelectRow(TItem item)
{
SelectedItem = item;
EditingCell = null;
StateHasChanged();
}
private void StartEdit(TItem item, ColumnDefinition<TItem> col)
{
EditingCell = (item, col);
}
private void EndEdit()
{
EditingCell = null;
}
private bool IsEditing(TItem item, ColumnDefinition<TItem> col)
{
return EditingCell.HasValue && EqualityComparer<TItem>.Default.Equals(EditingCell.Value.item, item) && EditingCell.Value.col == col;
}
private string GetCellValue(TItem item, ColumnDefinition<TItem> col)
{
var val = col.GetValue(item);
return val?.ToString() ?? "";
}
private void SetCellValue(TItem item, ColumnDefinition<TItem> col, string value)
{
col.SetValue(item, value);
}
private string GetRowClass(TItem item)
{
if (SelectedItem != null && EqualityComparer<TItem>.Default.Equals(SelectedItem, item))
return "table-primary";
return "";
}
private async Task OnKeyDown(KeyboardEventArgs e)
{
if (SelectedItem == null)
{
if (FilteredItems.Any())
{
SelectedItem = FilteredItems.First();
await ScrollToSelected();
}
return;
}
var list = FilteredItems.ToList();
var index = list.IndexOf(SelectedItem);
if (index == -1) return;
if (e.Key == "ArrowDown")
{
if (index < list.Count - 1)
{
SelectedItem = list[index + 1];
await ScrollToSelected();
}
}
else if (e.Key == "ArrowUp")
{
if (index > 0)
{
SelectedItem = list[index - 1];
await ScrollToSelected();
}
}
else if (e.Key == "Enter")
{
// Start editing first column of selected row
if (Columns.Any())
{
EditingCell = (SelectedItem, Columns[0]);
}
}
}
private async Task ScrollToSelected()
{
if (SelectedItem == null) return;
var index = FilteredItems.ToList().IndexOf(SelectedItem);
if (index == -1) return;
if (VirtualizeRef != null)
{
await VirtualizeRef.ScrollToItemAsync(index);
}
}
private void OnCellKeyDown(KeyboardEventArgs e, TItem item, ColumnDefinition<TItem> col)
{
if (e.Key == "Enter")
{
EndEdit();
SelectedItem = item;
}
else if (e.Key == "Escape")
{
EndEdit();
}
}
}
public class ColumnDefinition<T>
{
public string Header { get; set; } = "";
public Func<T, object?> GetValue { get; set; } = _ => null;
public Action<T, string> SetValue { get; set; } = (_, __) => { };
public ColumnDefinition(string header, Func<T, object?> getter, Action<T, string> setter)
{
Header = header;
GetValue = getter;
SetValue = setter;
}
}
How to use this component
In your parent page or component:
@page "/testgrid"
@using System.Globalization
<ExcelGrid TItem="Person" Items="People" Columns="Columns" />
@code {
List<Person> People = new();
List<ColumnDefinition<Person>> Columns = new();
protected override void OnInitialized()
{
People = Enumerable.Range(1, 1000).Select(i => new Person
{
Id = i,
Name = $"Name {i}",
Age = 20 + (i % 50)
}).ToList();
Columns = new List<ColumnDefinition<Person>>
{
new("Id", p => p.Id, (p,v) => { if(int.TryParse(v, out var val)) p.Id = val; }),
new("Name", p => p.Name, (p,v) => p.Name = v),
new("Age", p => p.Age, (p,v) => { if(int.TryParse(v, out var val)) p.Age = val; }),
};
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; } = "";
public int Age { get; set; }
}
}
Features included:
- Virtualization: Uses Blazor's built-in
Virtualize component for efficient rendering of large datasets.
- Sorting: Click column headers to sort ascending/descending.
- Filtering: Simple text filter applies to all columns.
- Cell editing: Click a cell to edit inline, press Enter to save, Escape to cancel.
- Keyboard navigation: Arrow up/down to move selection, Enter to edit.
- Row highlighting: Selected row is highlighted.
- Smooth scrolling: Uses
Virtualize.ScrollToItemAsync to scroll to selected row on arrow key navigation.
Notes & Next steps
- This is a minimal but functional grid foundation.
- You can extend it with:
- More complex filtering (per column)
- Multi-column sorting
- Copy/paste support
- Cell types (dropdowns, dates, etc.)
- Better styling and accessibility
- Performance tuning for very large datasets
If you want a production-ready grid with all Excel-like features, consider using third-party libraries like Telerik, Syncfusion, or Radzen grids, which have these features built-in and optimized.
If you want me to help extend this with any specific feature or polish, just ask!