Creating a Blazor component that functions like an Excel-like grid with virtualization, supporting:
- Cell navigation
- In-cell editing
- Sorting
- Filtering
- Virtualized scrolling
- Fast row scrolling using arrow keys
is a complex but very doable task in Blazor.
Below is a single .razor file that encapsulates all the functionality. It uses:
@key and @ref for cell tracking
InputText components for editable cells
ElementReference to focus cells dynamically
Virtualize component for performance
- Keyboard event handling for navigation
✅ Prerequisites:
Ensure your project supports Blazor WebAssembly or Server, and has Microsoft.AspNetCore.Components.Web.Extensions installed (for InputText, etc.).
📄 ExcelGrid.razor
@using System.ComponentModel
@using Microsoft.AspNetCore.Components.Web
@typeparam TItem
<div class="excel-grid-container">
<div class="grid-header">
@foreach (var column in Columns)
{
<div class="cell header-cell" @onclick="() => SortColumn(column)">
@column.Title
@if (SortColumnProperty == column.PropertyName)
{
<span>@(SortDirection == ListSortDirection.Ascending ? "▲" : "▼")</span>
}
</div>
}
</div>
<input type="text" placeholder="Filter..." @bind="FilterText" class="filter-input" />
<div class="grid-body" tabindex="0" @onkeydown="HandleKeyDown" @ref="GridBodyRef">
<Virtualize Items="@FilteredItems" Context="item" ItemSize="30">
<ItemContent>
@{
var item = context;
int rowIndex = RowIndex++;
<div class="row" style="display: contents;">
@foreach (var column in Columns)
{
var cellKey = $"{rowIndex}-{column.PropertyName}";
<div class="cell"
@key="cellKey"
@onclick="() => FocusCell(rowIndex, column.PropertyName)"
@ref="el => SetCellRef(cellKey, el)">
@if (FocusedRow == rowIndex && FocusedColumn == column.PropertyName)
{
<InputText @bind-Value="@GetPropertyValue(item, column.PropertyName)"
@onfocus="() => OnFocusCell(item, column.PropertyName)"
@onblur="SaveCellChanges"
autofocus />
}
else
{
@GetPropertyValue(item, column.PropertyName)
}
</div>
}
</div>
}
</ItemContent>
</Virtualize>
</div>
</div>
@code {
[Parameter] public List<GridColumn<TItem>> Columns { get; set; } = new();
[Parameter] public List<TItem> Items { get; set; } = new();
private string FilterText = "";
private string FocusedColumn = "";
private int FocusedRow = -1;
private Dictionary<string, ElementReference> CellRefs = new();
private ElementReference GridBodyRef;
private string CurrentPropertyName = "";
private object CurrentItem = null!;
private string SortColumnProperty = "";
private ListSortDirection SortDirection = ListSortDirection.Ascending;
private int RowIndex;
private void SetCellRef(string key, ElementReference el)
{
if (!CellRefs.ContainsKey(key))
{
CellRefs[key] = el;
}
}
private void FocusCell(int row, string column)
{
FocusedRow = row;
FocusedColumn = column;
StateHasChanged();
_ = JSRuntime.InvokeVoidAsync("focusElement", CellRefs[$"{row}-{column}"]);
}
private void OnFocusCell(object item, string propertyName)
{
CurrentItem = item;
CurrentPropertyName = propertyName;
}
private void SaveCellChanges()
{
if (CurrentItem != null && !string.IsNullOrEmpty(CurrentPropertyName))
{
var property = CurrentItem.GetType().GetProperty(CurrentPropertyName);
if (property != null)
{
// You can add more type support here
var value = JSRuntime.InvokeAsync<string>("getInputValue", CellRefs[$"{FocusedRow}-{FocusedColumn}"]).Result;
property.SetValue(CurrentItem, Convert.ChangeType(value, property.PropertyType));
}
}
}
private string GetPropertyValue(TItem item, string propertyName)
{
var prop = item.GetType().GetProperty(propertyName);
return prop?.GetValue(item)?.ToString() ?? "";
}
private void HandleKeyDown(KeyboardEventArgs e)
{
switch (e.Key)
{
case "ArrowDown":
FocusedRow = Math.Min(FocusedRow + 1, FilteredItems.Count - 1);
break;
case "ArrowUp":
FocusedRow = Math.Max(FocusedRow - 1, 0);
break;
case "ArrowRight":
var nextCol = Columns.IndexOf(Columns.FirstOrDefault(c => c.PropertyName == FocusedColumn)) + 1;
if (nextCol < Columns.Count)
FocusedColumn = Columns[nextCol].PropertyName;
break;
case "ArrowLeft":
var prevCol = Columns.IndexOf(Columns.FirstOrDefault(c => c.PropertyName == FocusedColumn)) - 1;
if (prevCol >= 0)
FocusedColumn = Columns[prevCol].PropertyName;
break;
default:
return;
}
FocusCell(FocusedRow, FocusedColumn);
}
private void SortColumn(GridColumn<TItem> column)
{
if (SortColumnProperty == column.PropertyName)
{
SortDirection = SortDirection == ListSortDirection.Ascending
? ListSortDirection.Descending
: ListSortDirection.Ascending;
}
else
{
SortColumnProperty = column.PropertyName;
SortDirection = ListSortDirection.Ascending;
}
var sortedList = Items.OrderByDynamic(SortColumnProperty, SortDirection).ToList();
Items.Clear();
Items.AddRange(sortedList);
}
private List<TItem> FilteredItems => string.IsNullOrWhiteSpace(FilterText)
? Items
: Items.Where(i => Columns.Any(c => GetPropertyValue(i, c.PropertyName)?.Contains(FilterText, StringComparison.OrdinalIgnoreCase) ?? false)).ToList();
protected override void OnParametersSet()
{
base.OnParametersSet();
FocusedRow = -1;
}
public class GridColumn<T>
{
public string PropertyName { get; set; } = "";
public string Title { get; set; } = "";
}
public static class DynamicSorter
{
public static IEnumerable<T> OrderByDynamic<T>(this IEnumerable<T> source, string propertyName, ListSortDirection direction)
{
var param = Expression.Parameter(typeof(T), "x");
var body = Expression.Property(param, propertyName);
var lambda = Expression.Lambda(body, param);
var method = typeof(Queryable).GetMethods()
.FirstOrDefault(m => m.Name == (direction == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending"))
?.MakeGenericMethod(typeof(T), body.Type);
return (IEnumerable<T>)method?.Invoke(null, new object[] { source.AsQueryable(), lambda })!;
}
}
}
🔧 Usage Example
Define a model:
public class Product
{
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
Use in a page:
@page "/grid-demo"
<ExcelGrid Items="@products" Columns="@columns" />
@code {
private List<Product> products = new()
{
new Product { Name = "Apple", Price = 1.2m },
new Product { Name = "Banana", Price = 0.5m },
new Product { Name = "Cherry", Price = 2.9m }
};
private List<ExcelGrid<Product>.GridColumn<Product>> columns = new()
{
new ExcelGrid<Product>.GridColumn<Product> { PropertyName = "Name", Title = "Product Name" },
new ExcelGrid<Product>.GridColumn<Product> { PropertyName = "Price", Title = "Price" }
};
}
📦 Required JavaScript Interop
Add this in _Host.cshtml (Blazor Server) or index.html (WebAssembly):
<script>
window.focusElement = (element) => {
element.focus();
};
window.getInputValue = (element) => {
return element.value;
};
</script>
✨ Features Recap
| Feature | Status |
|---|
| Virtualization | ✅ Yes (<Virtualize>) |
| Editable Cells | ✅ InputText inside focused cell |
| Sorting | ✅ Click headers |
| Filtering | ✅ Text input |
| Keyboard Navigation | ✅ Arrow keys |
| Fast Scrolling | ✅ Virtualized rendering |
💡 Tips
- Extend with validation, cell types (dropdowns, date pickers), etc.
- Consider debounced filtering for large datasets.
- Add keyboard shortcuts (Ctrl+Enter, Tab, Shift+Tab).
Let me know if you'd like this as a NuGet package, or enhanced with context menu, clipboard copy/paste, or multi-select!