Skip to content
# DataGrid **Also known as:** DataTable, TreeGrid, TreeList ## Description BitDataGrid displays an information-rich data table and gives people the tools to work through it: sorting, quick search and per-column filters, paging, grouping with aggregates, selection, inline editing, resizable/reorderable/frozen columns, master-detail and tree rows, keyboard cell navigation, row and column virtualization, and CSV/Excel export. Bind a list, an IQueryable executed at the source, or a callback for server-side paging or infinite scrolling. Use a data grid when information density is critical. ## Parameters | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | AddRowIcon | `BitIconInfo?` | null | The icon of the Add row button from an external icon library (ligature sets such as Material Icons included), shown beside its text or alone with ToolbarIconOnly. Takes precedence over AddRowIconName. | | AddRowIconName | `string?` | null | The name of the icon of the Add row button from the Fluent UI icon set of Bit.BlazorUI.Icons, whose stylesheet the app links, e.g. BitIconName.CirclePlus. | | AllowUnsorted | `bool` | true | Whether a third header click removes the sort (ascending → descending → unsorted). Overridable per column. | | AriaDescribedBy | `string?` | null | Id of the element that describes the grid. | | AriaLabelledBy | `string?` | null | Id of the element that names the grid, in place of AriaLabel. | | Bordered | `bool` | true | Draws the outer border and the column lines; the row lines are always drawn. | | CellNavigation | `bool` | false | Makes the data cells one tab stop: the arrows, Home/End and PageUp/PageDown move; Enter/F2 or typing edits; Esc cancels; Space selects (Shift+Space a range); Ctrl+A selects all; Delete deletes when Editable. Always on for Single SelectionMode and for Cell EditMode of an editable grid. While it is off no cell takes the focus, so the grid is announced as a table (role=table, its cells cell), or as a treegrid when it is a tree. | | ChildContent | `RenderFragment?` | null | Column definitions and other children. | | ChildrenProvider | `Func<TItem, Task<IEnumerable<TItem>?>>?` | null | Async children loader of a lazy tree grid: a node's children load on its first expand and are cached. Use instead of ChildrenSelector, with HasChildrenSelector. | | ChildrenSelector | `Func<TItem, IEnumerable<TItem>?>?` | null | Child selector that turns the grid into a tree grid: Items become the root nodes, and it returns a node's direct children, or null or an empty list for a leaf. Use only one of ChildrenSelector, ChildrenProvider and OnLoadChildren. | | Classes | `BitDataGridClassStyles?` | null | Custom CSS classes for the parts of the grid. | | ClearFiltersIcon | `BitIconInfo?` | null | The icon of the Clear filters button from an external icon library, shown beside its text or alone with ToolbarIconOnly. Takes precedence over ClearFiltersIconName. | | ClearFiltersIconName | `string?` | null | The name of the icon of the Clear filters button from the Fluent UI icon set of Bit.BlazorUI.Icons, e.g. BitIconName.FilterSolid. | | ClipboardCopy | `bool` | false | Enables Ctrl/⌘+C on a focused cell (with CellNavigation) and CopyToClipboardAsync, copying the selected or focused rows as tab-separated text with a header. | | ColumnChooserIcon | `BitIconInfo?` | null | The icon of the Columns button from an external icon library, shown beside its text or alone with ToolbarIconOnly. Takes precedence over ColumnChooserIconName. | | ColumnChooserIconName | `string?` | null | The name of the icon of the Columns button from the Fluent UI icon set of Bit.BlazorUI.Icons, e.g. BitIconName.TripleColumn. | | Columns | `RenderFragment?` | null | Alias of ChildContent for the column definitions (<Columns>...</Columns>); both are rendered when both are set. | | CsvExportIcon | `BitIconInfo?` | null | The icon of the CSV export button from an external icon library, shown beside its text or alone with ToolbarIconOnly. Takes precedence over CsvExportIconName. | | CsvExportIconName | `string?` | null | The name of the icon of the CSV export button from the Fluent UI icon set of Bit.BlazorUI.Icons, e.g. BitIconName.Download. | | DetailTemplate | `RenderFragment<TItem>?` | null | Expandable master-detail content rendered under a row. | | Editable | `bool` | false | Enables inline editing with a command column. The built-in editors write to a buffer that only Save writes to the row (raising OnRowSave). Only columns bound to a property with a setter are edited; overridable per column. Not available when TItem is a value type. | | EditMode | `BitDataGridEditMode` | BitDataGridEditMode.Row | Row edits the whole row with Save/Cancel; Cell edits one cell at a time (Enter, F2, double-click or typing opens; Enter, Tab or blur commits; Escape cancels). | | EmptyTemplate | `RenderFragment?` | null | Custom content shown in place of the rows when there are none - also when the filters or the search match none, in place of both Strings.EmptyText and Strings.NoMatchesText. | | ExcelExportIcon | `BitIconInfo?` | null | The icon of the Excel export button from an external icon library, shown beside its text or alone with ToolbarIconOnly. Takes precedence over ExcelExportIconName. | | ExcelExportIconName | `string?` | null | The name of the icon of the Excel export button from the Fluent UI icon set of Bit.BlazorUI.Icons, e.g. BitIconName.ExcelLogo. | | ExcelExportStyled | `bool` | false | Excel exports also carry the grid's rendered theme (colors, striping, borders, fonts), read from the DOM; plain styling without JS. | | ExpandDetailOnRowClick | `bool` | false | Toggles a row's detail when the row is clicked (selecting it too with SelectionMode). Clicks on the grid's own cells or on a control in a cell are excluded. | | ExpandedDetailItems | `IReadOnlyList<TItem>?` | null | The rows whose detail is expanded (two-way bindable). | | ExpandedDetailItemsChanged | `EventCallback<IReadOnlyList<TItem>>` | | Raised when the expanded detail rows change. | | ExportFileName | `string?` | null | Base name of the export files, e.g. "orders" for orders.csv. Defaults to "export". | | Filterable | `bool` | false | Renders a per-column filter row. A tree is pruned to the matching branches; not available on a lazy tree. | | FilterDebounce | `int` | 300 | Delay (ms) before a text/number filter applies; 0 applies each keystroke, a negative value only Enter or blur. | | FilterOperators | `bool` | false | Shows an operator dropdown next to the text/number/date filters (contains, starts with, =, ≠, >, <, is blank, is any of, ...). | | Groupable | `bool` | false | Adds a group-by toggle to the headers of the bound columns; grouping by several columns nests the groups. In-memory lists only: not with OnRead, OnLoadMore, an IQueryable or a tree. Overridable per column. | | GroupsInitiallyCollapsed | `bool` | false | Groups start collapsed instead of expanded. | | HasChildrenSelector | `Func<TItem, bool>?` | null | Whether an unloaded lazy node can have children, so it renders an expand toggle. ChildrenProvider and OnLoadChildren only. | | Height | `string?` | null | Height of the scroll viewport, e.g. "480px". Required for virtualization and infinite scrolling. | | Hoverable | `bool` | true | Highlights the row under the pointer. | | IsRowSelectionDisabled | `Func<TItem, bool>?` | null | Returns true for the rows that may not be selected. | | Items | `IEnumerable<TItem>?` | null | The client-side data source. An IQueryable<T> (e.g. an EF Core DbSet) has its filtering, sorting and paging executed at the source. | | KeyField | `Func<TItem, object>?` | null | Key selector for row identity - the selection, the edit, tree nodes and OnViewChange - so a refresh with new instances of the same rows keeps them. Defaults to reference equality. | | Loading | `bool` | false | Shows a loading row (LoadingTemplate, or a spinner) in place of the rows and marks the grid aria-busy. A server grid (OnRead) needs it for neither: it marks itself aria-busy while it reads, and shows the loading row while it has no rows to show yet. | | LoadingTemplate | `RenderFragment?` | null | Custom content replacing the spinner while Loading, and while a server grid reads its first rows. | | LoadMoreBatchSize | `int` | 50 | Rows fetched per batch in infinite-scrolling mode. | | MultiSort | `bool` | true | Lets a Ctrl/⌘ or Shift+click on a header add its column to the sort instead of replacing it. | | NewItemFactory | `Func<TItem>?` | null | Creates the new row of the toolbar Add button. | | OnCellClick | `EventCallback<BitDataGridCellEventArgs<TItem>>` | | Raised when a data cell is clicked; not on a control in it (see OnRowClick). | | OnCellContextMenu | `EventCallback<BitDataGridCellEventArgs<TItem>>` | | Raised when a data cell is right-clicked, suppressing the browser's menu; not on a control in it. | | OnCellDoubleClick | `EventCallback<BitDataGridCellEventArgs<TItem>>` | | Raised when a data cell is double-clicked; not on a control in it. | | OnDetailToggle | `EventCallback<BitDataGridDetailEventArgs<TItem>>` | | Raised when a row's detail is expanded or collapsed. | | OnFilterChange | `EventCallback<IReadOnlyList<BitDataGridFilterDescriptor>>` | | Raised with the new filters whenever the filtering changes. | | OnGroupChange | `EventCallback<IReadOnlyList<BitDataGridGroupDescriptor>>` | | Raised with the new groups whenever the grouping changes. | | OnLoadChildren | `Func<BitDataGridChildrenRequest<TItem>, Task<IEnumerable<TItem>?>>?` | null | ChildrenProvider with a cancellation token, cancelled once the grid no longer needs the children (new Items, or the grid is disposed). Use only one of ChildrenSelector, ChildrenProvider and OnLoadChildren. | | OnLoadMore | `Func<BitDataGridReadRequest, Task<BitDataGridReadResult<TItem>>>?` | null | Infinite-scrolling callback, appending a batch as the user scrolls to the end. Exports request all rows with Take = null, so honor a null Take. | | OnPageChange | `EventCallback<int>` | | Raised with the new 1-based page when the page or the page size changes. | | OnRead | `Func<BitDataGridReadRequest, Task<BitDataGridReadResult<TItem>>>?` | null | Server-side data callback; the grid hands it the sorting, filtering, searching and paging and shows the page it returns with its TotalCount. Grouping is not offered in this mode, and the grid reads again only when the request changes - call RefreshAsync after the data does. | | OnReadError | `EventCallback<Exception>` | | Raised with what OnRead threw reading the rows the grid shows. Setting it makes the grid handle the failure: an error row with a Retry button in place of the rows. Without it the exception propagates. A failed export never raises it. | | OnRowCancel | `EventCallback<TItem>` | | Raised when an edit is cancelled. | | OnRowClick | `EventCallback<TItem>` | | Raised when a row is clicked. A click on a control in a cell (a button, link, field, ARIA widget, focusable or data-bit-interactive element, or anything in a dialog or grid in the cell) raises neither this nor OnCellClick, and selects or expands nothing. data-bit-interactive="false" opts a control out. | | OnRowCreate | `EventCallback<TItem>` | | Raised when a new row is created. | | OnRowDelete | `EventCallback<TItem>` | | Raised when a row is deleted (Delete button or Delete key). | | OnRowDoubleClick | `EventCallback<TItem>` | | Raised when a row is double-clicked, e.g. to open the record or BeginEdit; not on a control in a cell. | | OnRowReorder | `EventCallback<BitDataGridRowReorderEventArgs<TItem>>` | | Raised when a row is dropped onto another row. The grid moves the item itself when Items is a mutable IList<T>; otherwise the indices are null and the move is yours to make. | | OnRowSave | `EventCallback<TItem>` | | Raised when an edited row is saved. | | OnSortChange | `EventCallback<IReadOnlyList<BitDataGridSortDescriptor>>` | | Raised with the new sorts whenever the sorting changes. | | OnStateChange | `EventCallback<BitDataGridState>` | | Raised with a GetState snapshot after any state it captures changes (sorts, filters, search, groups, page, column layout), for persisting the view. Not raised by ApplyStateAsync. | | OnViewChange | `EventCallback<IReadOnlyList<TItem>>` | | Raised with the rows of the view across every page (see GetViewItems) when the search, filters, sorts or Items change them, to keep a chart or a map in step. Rows are matched by KeyField. List, tree and IQueryable sources only; use GetViewItemsAsync in server/infinite modes. | | Pageable | `bool` | false | Splits the rows into pages and renders the pager. Ignored while the rows are grouped, in a tree and with OnLoadMore, which show every row they hold. | | PagerPlacement | `BitPlacement` | BitPlacement.Bottom | Where the pager renders: Top, Bottom or TopAndBottom; any other value is Bottom. | | PageSize | `int` | 20 | The number of rows per page. | | PageSizeOptions | `int[]` | { 10, 20, 50, 100 } | The page sizes offered in the pager; the PageSize in effect is added when it is not among them. | | Reorderable | `bool` | false | Lets the columns be reordered by dragging a header, Ctrl+Left/Right, or the column chooser. | | Resizable | `bool` | false | Lets the columns be resized by dragging a header's edge, double-clicking it (fit), or with the keyboard on it. | | RowClass | `Func<TItem, string?>?` | null | Per-row CSS class selector, appended after the grid's own row classes. | | RowHeight | `float` | 36 | The minimum height of a row in px; with Virtualize, the exact height of every row. | | RowHeightSelector | `Func<TItem, float>?` | null | Per-row minimum height in px, in place of RowHeight (ignored while virtualizing). | | RowReorderable | `bool` | false | Enables drag-and-drop row reordering (pointer, or the drag handle's arrow keys). Paused while the view is sorted, filtered, searched or grouped; not available in a tree, with OnRead, OnLoadMore or an IQueryable. | | RowStyle | `Func<TItem, string?>?` | null | Per-row inline style selector. | | SearchDebounce | `int` | 300 | Delay (ms) after the last keystroke before the search applies; 0 applies each keystroke. | | SearchText | `string?` | null | The quick-search term (two-way bindable). | | SearchTextChanged | `EventCallback<string?>` | | Raised when the quick-search term changes. | | SelectedItems | `IReadOnlyList<TItem>?` | null | The selected items (two-way bindable). | | SelectedItemsChanged | `EventCallback<IReadOnlyList<TItem>>` | | Raised when the selection changes. | | SelectionMode | `BitSelectionMode` | BitSelectionMode.None | None, Single (a row click or Space; turns CellNavigation on) or Multiple (a checkbox column). | | ShowCellTooltips | `bool` | false | Gives each value cell a native tooltip with its full text. Overridable per column (ShowTooltip); Template cells are excluded. | | ShowColumnChooser | `bool` | false | Renders the column chooser button, to show, hide and (with Reorderable) move columns. | | ShowCsvExport | `bool` | false | Renders a CSV export button, exporting all matching rows in every data mode. | | ShowDetailToggle | `bool` | true | Renders the expand/collapse column while a DetailTemplate is set. Turn it off to drive the details from row clicks or code. | | ShowExcelExport | `bool` | false | Renders an Excel (.xlsx) export button. Built in-process, exporting all matching rows with the grid's layout (frozen header and columns, widths, merged ColSpan cells). | | ShowFooter | `bool` | false | Renders the footer/aggregate row. | | ShowHeader | `bool` | true | Renders the header rows (titles, header groups and the filter row). | | ShowRowNumbers | `bool` | false | Renders a leading gutter numbering the rows by their position in the whole dataset, across pages and batches. Never exported or copied. | | ShowSearchBox | `bool` | false | Renders a toolbar quick-search box filtering the rows across every searchable column, ignoring case. Sent as BitDataGridReadRequest.Search in server/infinite modes; not available on a lazy tree (ChildrenProvider, OnLoadChildren). | | ShowToolbar | `bool` | false | Renders the toolbar with its Clear filters button. Search, export, the column chooser, Add and ToolbarTemplate show it on their own. | | Sortable | `bool` | true | Enables column sorting by clicking headers. Overridable per column. | | Strings | `BitDataGridStrings` | new() | All user-visible strings; assign a customized instance to localize. | | Striped | `bool` | true | Renders alternate-row striping. | | Styles | `BitDataGridClassStyles?` | null | Custom CSS styles for the parts of the grid. | | ToolbarIconOnly | `bool` | false | Renders the toolbar's buttons (Add row, Clear filters, the exports, Columns) as icons alone; each one's localized text stays its accessible name and is shown in a tooltip on hover, focus and touch. A button given no icon draws a built-in one (Add, ClearFilter, TextDocument, ExcelDocument, ColumnOptions) that needs no icon package. | | ToolbarTemplate | `RenderFragment?` | null | Custom content at the toolbar's start. | | TreeInitiallyExpanded | `bool` | false | Whether the tree nodes start expanded. Ignored in lazy mode. | | Virtualize | `bool` | false | Renders only the visible rows. Requires Height and RowHeight; server mode without paging fetches the rows as they scroll in. A grouped view is virtualized too, its group rows RowHeight tall on one line. Ignores RowHeightSelector, WrapCellText and the height of expanded detail rows. | | VirtualizeColumns | `bool` | false | Renders only the columns near the horizontal viewport. Requires px column widths; not applied with header groups or ColSpans. | | WrapCellText | `bool` | false | Wraps long headers and values onto several lines instead of clipping them. Overridable per column (WrapText); ignored while virtualizing. | | AriaLabel | `string?` | null | Gets or sets the accessible label for the component, used by assistive technologies. | | Class | `string?` | null | Gets or sets the CSS class name(s) to apply to the rendered element. | | Dir | `BitDir?` | null | Gets or sets the text directionality for the component's content. | | Disabled | `bool` | false | Gets or sets a value indicating whether the component is disabled and cannot respond to user interaction. | | ForceAnimation | `bool` | false | Gets or sets a value indicating whether the component's animations play at their full duration even when reduced motion is requested. | | HtmlAttributes | `Dictionary<string, object>` | new Dictionary<string, object>() | Captures additional HTML attributes to be applied to the rendered element, in addition to the component's parameters. An attribute written on the component wins over an entry of the same name. | | Id | `string?` | null | Gets or sets the unique identifier for the component's root element. | | Style | `string?` | null | Gets or sets the CSS style string to apply to the rendered element. | | TabIndex | `string?` | null | Gets or sets the tab order index for the component when navigating with the keyboard. | | Visibility | `BitVisibility` | BitVisibility.Visible | Gets or sets the visibility state (visible, hidden, or collapsed) of the component. | ## Public Members | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | RefreshAsync | `Task` | | Recomputes the view (filter, sort, group, page) and re-renders. | | SortByAsync | `Task` | | SortByAsync(columnId, direction, additive) - sorts by a column; BitDataGridSortDirection.None removes the sort. | | ClearSortsAsync | `Task` | | Removes all the sorts. | | ApplyFilterAsync | `Task` | | ApplyFilterAsync(columnId, operator, value) - applies a filter, replacing the column's existing one. | | ApplyRangeFilterAsync | `Task` | | ApplyRangeFilterAsync(columnId, from, toExclusive) - applies a half-open range filter (>= from AND < toExclusive) as two comparison filters. | | ClearFilterAsync | `Task` | | ClearFilterAsync(columnId) - removes a column's filters. | | ClearFiltersAsync | `Task` | | Removes all the column filters. | | GroupByAsync | `Task` | | GroupByAsync(columnId) - adds the column as the next grouping level. | | UngroupAsync | `Task` | | UngroupAsync(columnId) - removes the column's grouping level. | | ClearGroupsAsync | `Task` | | Removes all the groupings. | | ExpandAllGroupsAsync | `Task` | | Expands every group, including the ones built later. | | CollapseAllGroupsAsync | `Task` | | Collapses every group, including the ones built later. | | SearchAsync | `Task` | | SearchAsync(text) - applies the quick-search term (null clears it) and goes to the first page. | | ActiveSearch | `string?` | null | The active quick-search term, or null. | | SelectAllAsync | `Task` | | Selects every selectable row of the view (only the loaded ones in server, queryable and infinite modes). Multiple mode only. | | ClearSelectionAsync | `Task` | | Clears the row selection. | | CopyToClipboardAsync | `Task<int>` | | CopyToClipboardAsync() / CopyToClipboardAsync(fallbackRow) - copies the selected rows (or the fallback row) as tab-separated text and returns how many were copied; 0 without a clipboard. | | AutoFitColumnAsync | `Task` | | AutoFitColumnAsync(columnId) - sizes a column to its widest content. | | AutoFitAllColumnsAsync | `Task` | | Auto-fits every visible column. | | GoToPageAsync | `Task` | | GoToPageAsync(page) - goes to a 1-based page (clamped). | | MoveColumnAsync | `Task` | | MoveColumnAsync(columnId, index) - moves a column to a 0-based position among all the columns. | | SetPageSizeAsync | `Task` | | SetPageSizeAsync(size) - changes the page size and goes to the first page. | | GetViewItems | `IReadOnlyList<TItem>` | | The rows of the view across every page, in display order. Server/infinite modes return only the loaded rows; use GetViewItemsAsync there. | | GetViewItemsAsync | `Task<IReadOnlyList<TItem>>` | | GetViewItemsAsync(cancellationToken) - the rows of the view across every page in every mode; server/infinite modes read them with an unpaged request (Take = null). | | RevealItemAsync | `Task<bool>` | | RevealItemAsync(item) - pages to, expands to and scrolls to a row of the view; false when the row is not in it. | | GetState | `BitDataGridState` | | Captures the user-adjustable state (page, search, sorts, filters, groups, column layout) as a serializable snapshot. | | ApplyStateAsync | `Task` | | ApplyStateAsync(state) - restores a GetState snapshot. | | ExportCsvAsync | `Task` | | ExportCsvAsync(selectedOnly) - downloads all the matching rows (or the selected ones) as CSV, in every data mode. | | ToCsv | `string` | | ToCsv(selectedOnly) - builds the CSV synchronously; server/infinite modes cover only the loaded rows (use ToCsvAsync). | | ToCsvAsync | `Task<string>` | | ToCsvAsync(selectedOnly) - builds the CSV of all the matching (or selected) rows in every mode. | | ToExcelAsync | `Task<byte[]>` | | ToExcelAsync(selectedOnly) - builds an .xlsx of all the matching (or selected) rows with native cell types and the grid's layout (and theme, with ExcelExportStyled). | | ExportExcelAsync | `Task` | | ExportExcelAsync(selectedOnly) - builds the .xlsx and downloads it. | | ActiveSorts | `IReadOnlyList<BitDataGridSortDescriptor>` | [] | The active sorts, in priority order. | | ActiveFilters | `IReadOnlyList<BitDataGridFilterDescriptor>` | [] | The active filters. | | ActiveGroups | `IReadOnlyList<BitDataGridGroupDescriptor>` | [] | The active groups, in nesting order. | | TotalCount | `int` | 0 | The rows of the filtered view; the server's total in server mode. | | TotalPages | `int` | 1 | The number of pages while paging. | | CurrentPage | `int` | 1 | The 1-based current page. | | ExpandAllAsync | `Task` | | Expands every tree node (tree mode only). | | CollapseAllAsync | `Task` | | Collapses every tree node (tree mode only). | | IsDetailExpanded | `bool` | | IsDetailExpanded(item) - whether the row's detail is expanded. | | ExpandDetailAsync | `Task` | | ExpandDetailAsync(item) - expands the row's detail. | | CollapseDetailAsync | `Task` | | CollapseDetailAsync(item) - collapses the row's detail. | | ToggleDetailAsync | `Task` | | ToggleDetailAsync(item) - toggles the row's detail. | | SetDetailExpandedAsync | `Task` | | SetDetailExpandedAsync(item, expanded) - expands or collapses the row's detail. | | ExpandAllDetailsAsync | `Task` | | Expands the detail of every row of the view (only the loaded rows in server, queryable and infinite modes). | | CollapseAllDetailsAsync | `Task` | | Collapses every expanded detail. | | EditingItem | `TItem?` | null | The row being edited, or null. | | EditingColumnId | `string?` | null | The column of the cell being edited in Cell mode, or null. | | BeginEditAsync | `Task` | | BeginEditAsync(item, columnId) - opens an edit at a cell and focuses its editor. | | BeginEdit | `void` | | BeginEdit(item) - puts a row into edit mode, as its Edit button does. | | CommitEditAsync | `Task` | | Saves the open edit and raises OnRowSave; refused while a value is invalid. | | CancelEditAsync | `Task` | | Abandons the open edit, restoring the row, and raises OnRowCancel. | | AddNewRowAsync | `Task` | | Adds a row from NewItemFactory and opens it for editing, as the toolbar Add button does. | | DeleteRowAsync | `Task` | | DeleteRowAsync(item) - deselects the row and raises OnRowDelete for the caller to remove it. | | UniqueId | `Guid` | Guid.NewGuid() | Gets the readonly unique identifier for the component's root element, assigned when the component instance is constructed. | | RootElement | `ElementReference` | | Gets the reference to the root HTML element associated with this component. | ## Enums ### BitTextAlign Enum | Name | Value | Description | | :--- | :--- | :---------- | | Start | 0 | The leading edge, whatever the text direction. | | End | 1 | The trailing edge, whatever the text direction. | | Left | 2 | The left edge, whatever the text direction. | | Right | 3 | The right edge, whatever the text direction. | | Center | 4 | Centers the lines. | | Justify | 5 | Lines up both edges of every line but the last. | | JustifyAll | 6 | Justifies the last line too. Not implemented by browsers yet. | | MatchParent | 7 | Inherits, resolving start/end against the parent's direction. | | Inherit | 8 | Takes the parent's alignment. | | Initial | 9 | Takes the initial value. | | Revert | 10 | Reverts to the user agent or user stylesheet value. | | RevertLayer | 11 | Reverts to the previous cascade layer's value. | | Unset | 12 | Inherits, or takes the initial value where not inherited. | ### BitDataGridSortDirection Enum | Name | Value | Description | | :--- | :--- | :---------- | | None | 0 | Not sorted. SortByAsync removes the sort with it; a group keeps its keys in first-met order. | | Ascending | 1 | Smallest to largest. | | Descending | 2 | Largest to smallest. | ### BitDataGridEditMode Enum | Name | Value | Description | | :--- | :--- | :---------- | | Row | 0 | The whole row, with Save/Cancel. | | Cell | 1 | One cell at a time; Enter, Tab or blur commits, Escape cancels. | ### BitSelectionMode Enum | Name | Value | Description | | :--- | :--- | :---------- | | None | 0 | Nothing can be selected: the items act as plain content or as plain action buttons. | | Single | 1 | At most one item can be selected at a time, so selecting one clears the one before it. | | Multiple | 2 | Any number of items can be selected at the same time. | ### BitDataGridAggregateType Enum | Name | Value | Description | | :--- | :--- | :---------- | | None | 0 | No aggregate, unless the column has an AggregateBy. | | Sum | 1 | The total of the numeric values. | | Average | 2 | The mean of the numeric values, or 0. | | Count | 3 | The number of rows. | | Min | 4 | The smallest non-null value. | | Max | 5 | The largest non-null value. | | Custom | 6 | Produced by the column's AggregateBy. | ### BitPlacement Enum | Name | Value | Description | | :--- | :--- | :---------- | | Top | 0 | The top edge. | | Bottom | 1 | The bottom edge. | | Start | 2 | The edge the reading direction starts from - the left in LTR, the right in RTL. On the vertical axis, which does not turn around, it is the top. | | End | 3 | The edge the reading direction ends at - the right in LTR, the left in RTL. On the vertical axis, which does not turn around, it is the bottom. | | Left | 4 | The left edge, in both reading directions. | | Right | 5 | The right edge, in both reading directions. | | Center | 6 | The middle of the axis, against neither edge. | | TopAndBottom | 7 | Both edges of the block axis at once. | | StartAndEnd | 8 | Both edges of the inline axis at once, following the reading direction the way Start and End do. | ### BitDataGridColumnDataType Enum | Name | Value | Description | | :--- | :--- | :---------- | | Auto | 0 | Inferred from the property type (bool, enum, date, numeric; otherwise Text). | | Text | 1 | A text box with the text operators. | | Number | 2 | A numeric text box with the comparison operators. | | Boolean | 3 | A true/false dropdown. | | Date | 4 | A date picker, without a time of day. | | DateTime | 5 | A date picker; equality matches the whole day. | | DateTimeOffset | 6 | A date picker; equality matches the whole day. | | Enum | 7 | A dropdown of the enum's names. | ### BitDataGridFilterOperator Enum | Name | Value | Description | | :--- | :--- | :---------- | | Unspecified | 0 | No operator; the filter is ignored. | | Contains | 1 | The text contains the term, ignoring case. | | DoesNotContain | 2 | The text does not contain the term, ignoring case. | | StartsWith | 3 | The text starts with the term, ignoring case. | | EndsWith | 4 | The text ends with the term, ignoring case. | | Equals | 5 | Equals the operand; a null operand matches nulls. | | NotEquals | 6 | Does not equal the operand. | | GreaterThan | 7 | Greater than the operand; nulls never match. | | GreaterThanOrEqual | 8 | Greater than or equal to the operand; nulls never match. | | LessThan | 9 | Less than the operand; nulls never match. | | LessThanOrEqual | 10 | Less than or equal to the operand; nulls never match. | | IsEmpty | 11 | Null or empty text; takes no operand. | | IsNotEmpty | 12 | Neither null nor empty text; takes no operand. | | In | 13 | Equals a member of the Value collection. | | NotIn | 14 | Equals no member of the Value collection. | ### BitVisibility Enum | Name | Value | Description | | :--- | :--- | :---------- | | Visible | 0 | The content of the component is visible. | | Hidden | 1 | The content of the component is hidden, but the space it takes on the page remains (visibility:hidden). | | Collapsed | 2 | The component is hidden (display:none). | ### BitDir Enum | Name | Value | Description | | :--- | :--- | :---------- | | Ltr | 0 | Ltr (left to right) is to be used for languages that are written from the left to the right (like English). | | Rtl | 1 | Rtl (right to left) is to be used for languages that are written from the right to the left (like Arabic). | | Auto | 2 | Auto lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element. | ## Sub Classes ### BitDataGridClassStyles Properties Defines per-part CSS class/style values for BitDataGrid. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | Root | `string?` | null | Custom class or style of the root element. | | Toolbar | `string?` | null | Custom class or style of the toolbar. | | ColumnChooser | `string?` | null | Custom class or style of the column chooser. | | Viewport | `string?` | null | Custom class or style of the scrolling viewport. | | HeaderRow | `string?` | null | Custom class or style of the column titles row. | | HeaderCell | `string?` | null | Custom class or style of each header cell, before the column's HeaderClass. | | FilterRow | `string?` | null | Custom class or style of the filter row. | | Row | `string?` | null | Custom class or style of each data row, before RowClass/RowStyle. | | SelectedRow | `string?` | null | Custom class or style of each selected row, after Row. | | Cell | `string?` | null | Custom class or style of each data cell, before the column's CellClass. | | GroupRow | `string?` | null | Custom class or style of each group header cell. | | DetailRow | `string?` | null | Custom class or style of each detail row's content. | | FooterRow | `string?` | null | Custom class or style of the footer row. | | Pager | `string?` | null | Custom class or style of the pager. | | Empty | `string?` | null | Custom class or style of the empty message cell. | | Loading | `string?` | null | Custom class or style of the loading indicator cell. | | ReadError | `string?` | null | Custom class or style of the cell showing a failed read and its Retry button. | ### BitDataGridColumn Properties A column of a BitDataGrid, placed in its child content. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | Field | `string?` | null | Name of the bound property; supports nested paths ("Address.City"). Prefer Property. | | Property | `Expression<Func<TItem, object?>>?` | null | Typed selector of the bound property, e.g. p => p.Address.City. Refactor-safe; takes precedence over Field. | | ColumnId | `string?` | null | Stable column identifier, used by the sort, filter, group and state APIs and sent to OnRead. Defaults to the Property/Field path; a template-only column otherwise gets a generated id that changes between instances, so give it one. | | Title | `string?` | null | Header text. Defaults to the humanized Property/Field name. | | Width | `string?` | null | CSS width, e.g. "120px" or "20%"; null shares the remaining space. | | MinWidth | `int` | 60 | Minimum resize width in px. | | MaxWidth | `int?` | null | Maximum resize width in px. | | Sortable | `bool?` | null | Overrides the grid's Sortable. A template-only column sorts only through SortBy (in-memory sources) or ServerSortable (server/infinite modes). | | SortBy | `Func<TItem, object?>?` | null | Custom sort key, making a template-only column sortable; in-memory sources only. | | ServerSortable | `bool` | false | Lets a template-only column sort in server/infinite modes, sending its ColumnId (required) in the request. | | SortDescendingFirst | `bool` | false | The first header click sorts descending. | | AllowUnsorted | `bool?` | null | Overrides the grid's AllowUnsorted. | | Comparer | `IComparer<object?>?` | null | Custom comparer of the column's sort keys; client-side only. | | Validate | `Func<TItem, object?, string?>?` | null | Inline-edit validator: returns an error message to reject the value, or null to accept it. | | Filterable | `bool?` | null | Overrides the grid's Filterable. | | FilterOperators | `bool?` | null | Overrides the grid's FilterOperators. | | FilterTemplate | `RenderFragment<BitDataGridFilterContext>?` | null | Custom filter editor; its context carries the filter and ApplyAsync/ApplyRangeAsync/ClearAsync. | | Resizable | `bool?` | null | Overrides the grid's Resizable. | | Reorderable | `bool?` | null | Overrides the grid's Reorderable. | | Editable | `bool?` | null | Overrides the grid's Editable. | | Groupable | `bool?` | null | Overrides the grid's Groupable. | | Searchable | `bool?` | null | Whether the quick search covers the column. Defaults to the bound (or ExportValue) columns. | | Exportable | `bool?` | null | Whether exports include the column. Defaults to the columns with a value (a bound field or ExportValue). | | ExportValue | `Func<TItem, object?>?` | null | The value exports and the clipboard use instead of the bound field. | | ShowTooltip | `bool?` | null | Overrides the grid's ShowCellTooltips. | | WrapText | `bool?` | null | Overrides the grid's WrapCellText. | | Frozen | `bool` | false | Pins the column to the start edge while scrolling horizontally. | | FrozenEnd | `bool` | false | Pins the column to the end edge (the right in LTR, the left in RTL). Ignored when Frozen is set. | | Group | `string?` | null | Header group name; consecutive columns sharing it render under one spanning header. | | ColSpan | `Func<TItem, int?>?` | null | Per-row column span: how many visible columns the cell covers, from its own; null or anything below 2 covers just its own, and a span is cut at the last column. Turns VirtualizeColumns off. | | Visible | `bool` | true | Whether the column is visible. The column chooser flips it at runtime; a hidden column is left out of exports and copies too. | | RowHeader | `bool` | false | Makes the cells the headers of their rows (role rowheader), naming the row for screen readers. | | Align | `BitTextAlign` | BitTextAlign.Start | Horizontal alignment of the cells: Start, Center, End, Left or Right; any other value is Start. | | Format | `string?` | null | A .NET format string applied in the current culture, e.g. "C2" or "yyyy-MM-dd"; used by the cells, exports and the quick search. | | ValueText | `Func<object, string?>?` | null | The text a value is shown as (e.g. a translated enum name) in the cells, tooltips, group headers, Min/Max aggregates, enum and boolean filter and editor options, and what the in-memory quick search and text filters match; null keeps the default. Display only: exports keep the value itself (use ExportValue for other text). An enum member otherwise shows its [Display] name, unless a Format is set. | | DataType | `BitDataGridColumnDataType` | BitDataGridColumnDataType.Auto | The data type picking the editor and filter. | | Aggregate | `BitDataGridAggregateType` | BitDataGridAggregateType.None | The footer/group aggregate function. | | AggregateBy | `Func<IReadOnlyList<TItem>, object?>?` | null | Custom aggregate function (e.g. a distinct count); takes precedence over Aggregate. | | AggregateFormat | `string?` | null | Format of the aggregate value; falls back to Format. | | HeaderClass | `string?` | null | CSS class of the header cell. | | CellClass | `string?` | null | CSS class of each data cell. | | CellClassSelector | `Func<TItem, string?>?` | null | Per-row CSS class of the cells, after CellClass. | | CellStyleSelector | `Func<TItem, string?>?` | null | Per-row inline style of the cells. Prefer color/font to background, which hides selection and hover. | | Template | `RenderFragment<TItem>?` | null | Custom data cell content. | | HeaderTemplate | `RenderFragment?` | null | Custom header cell content. | | EditTemplate | `RenderFragment<TItem>?` | null | Custom editor in edit mode. It binds straight to the row rather than to the edit buffer; Cancel restores the values the row had when the edit began. Opened by Enter or F2, not by typing. | | FooterTemplate | `RenderFragment<BitDataGridAggregateResult>?` | null | Custom footer cell content, rendered only where the column has an Aggregate or AggregateBy. | ### BitDataGridReadRequest Properties What the grid asks of OnRead/OnLoadMore. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | Skip | `int` | 0 | Zero-based number of items to skip. | | Take | `int?` | null | Maximum number of items to return; null means all. | | Sorts | `IReadOnlyList<BitDataGridSortDescriptor>` | [] | The active sorts, by priority. | | Filters | `IReadOnlyList<BitDataGridFilterDescriptor>` | [] | The active filters. | | Groups | `IReadOnlyList<BitDataGridGroupDescriptor>` | [] | The active groups, in nesting order. | | Search | `string?` | null | The quick-search term to match across the searchable columns, or null. | | Aggregates | `IReadOnlyList<BitDataGridAggregateDescriptor>` | [] | The aggregates the footer shows, one per aggregating column: compute them over the whole filtered data and return them in the result's Aggregates. Empty for OnLoadMore and export reads. | | CancellationToken | `CancellationToken` | | Cancelled when a newer request supersedes this one. | ### BitDataGridReadResult<TItem> Properties The result of OnRead/OnLoadMore. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | Items | `IReadOnlyList<TItem>` | | The items of the current page/window. | | TotalCount | `int` | | The total of the matching items over every page; 0 in infinite mode, which ignores it. A positive total smaller than Items.Count is refused. | | Aggregates | `IReadOnlyList<BitDataGridAggregateResult>?` | null | Aggregates over the whole filtered data, shown in the footer instead of the page's own. | ### BitDataGridChildrenRequest<TItem> Properties What a lazy tree grid asks of OnLoadChildren. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | Parent | `TItem` | | The node whose direct children are requested. | | CancellationToken | `CancellationToken` | | Cancelled once the grid no longer needs the children: new Items replaced the hierarchy, or the grid is disposed. Collapsing the node does not cancel it. | ### BitDataGridCellEventArgs<TItem> Properties Arguments of the cell events. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | Item | `TItem` | | The row item. | | Column | `BitDataGridColumn<TItem>` | | The cell's column. | | ColumnId | `string` | | The column's identifier. | | ColumnTitle | `string` | | The column's title. | | Value | `object?` | null | The cell's raw value. | | Mouse | `MouseEventArgs` | | The browser mouse event. | ### BitDataGridDetailEventArgs<TItem> Properties Arguments of a row's detail toggle. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | Item | `TItem` | | The toggled row. | | Expanded | `bool` | | Whether the detail was expanded. | ### BitDataGridRowReorderEventArgs<TItem> Properties Arguments of a row drop. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | DraggedItem | `TItem` | | The dragged row. | | TargetItem | `TItem` | | The drop-target row. | | FromIndex | `int?` | | The original index, or null when Items is not an indexable list. | | ToIndex | `int?` | | The destination index, or null when Items is not an indexable list. | ### BitDataGridSortDescriptor Properties A column's sort (in BitDataGridReadRequest.Sorts). | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | ColumnId | `string` | | The sorted column's identifier. | | Direction | `BitDataGridSortDirection` | BitDataGridSortDirection.Ascending | The sort direction. | | Priority | `int` | int.MaxValue | Multi-sort priority (1 = primary). | ### BitDataGridFilterDescriptor Properties A column's filter (in BitDataGridReadRequest.Filters). | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | ColumnId | `string` | | The filtered column's identifier. | | Operator | `BitDataGridFilterOperator` | BitDataGridFilterOperator.Unspecified | The comparison operator; Unspecified applies no filter. | | Value | `object?` | null | The operand; a collection for In/NotIn. | ### BitDataGridFilterContext Properties The context of a column's FilterTemplate: its filter and the calls that change it. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | ColumnId | `string` | | The filtered column's identifier. | | Title | `string` | | The column's header text. | | Label | `string` | | The editor's accessible name ("Filter by {Title}"). | | ValueType | `Type?` | null | The bound member's type, Nullable<T> unwrapped. | | Disabled | `bool` | | Whether the grid is disabled. | | Filters | `IReadOnlyList<BitDataGridFilterDescriptor>` | | The column's filters: none, one, or a range's two halves. | | IsActive | `bool` | | Whether the column is filtered. | | Operator | `BitDataGridFilterOperator` | | The first filter's operator, or Unspecified. | | Value | `object?` | | The first filter's value, or null. | | ApplyAsync | `Task (BitDataGridFilterOperator, object?)` | | Replaces the filter; an empty value clears it. | | ApplyRangeAsync | `Task (object?, object?)` | | Replaces the filter with a half-open range (>= from AND < toExclusive). | | ClearAsync | `Task ()` | | Removes the filter. | ### BitDataGridGroupDescriptor Properties A column's grouping. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | ColumnId | `string` | | The grouped column's identifier. | | Direction | `BitDataGridSortDirection` | BitDataGridSortDirection.Ascending | The sort direction of the group keys. | ### BitDataGridAggregateDescriptor Properties An aggregate the footer shows (in BitDataGridReadRequest.Aggregates). | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | ColumnId | `string` | | The aggregating column's identifier. | | Type | `BitDataGridAggregateType` | | The column's aggregate function; Custom for a column with its own AggregateBy, which the server computes its own way. | ### BitDataGridAggregateResult Properties A computed footer or group aggregate (passed to FooterTemplate). | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | ColumnId | `string` | | The aggregated column's identifier. | | Type | `BitDataGridAggregateType` | | The aggregate function. | | Value | `object?` | null | The raw value. | | FormattedValue | `string` | string.Empty | The value formatted with AggregateFormat/Format. | ### BitDataGridState Properties A serializable snapshot of the user-adjustable state, from GetState() for ApplyStateAsync(). | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | CurrentPage | `int` | 1 | The 1-based current page. | | PageSize | `int?` | null | The user-chosen page size, or null for the PageSize parameter. | | Search | `string?` | null | The quick-search term, or null. | | Sorts | `List<BitDataGridSortDescriptor>` | [] | The active sorts. | | Filters | `List<BitDataGridFilterDescriptor>` | [] | The active filters. | | Groups | `List<BitDataGridGroupDescriptor>` | [] | The active groups. | | GroupsCollapsed | `bool` | false | Whether the groups were collapsed by default. | | GroupExpansionOverrides | `List<string>` | [] | The paths of the groups whose expansion differs from GroupsCollapsed. Tree expansion is not captured. | | Columns | `List<BitDataGridColumnState>` | [] | The column layout. | ### BitDataGridColumnState Properties A column's layout in BitDataGridState.Columns. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | ColumnId | `string` | string.Empty | The column's identifier. | | Visible | `bool` | true | Whether the column is shown. | | Width | `double?` | null | The resized width in px, or null. | | Order | `int` | 0 | The display position among all the columns. | ### BitDataGridStrings Properties All the user-visible and screen-reader strings of the grid, in English by default; assign a customized instance to Strings to localize. | Name | Type | Default Value | Description | | :--- | :--- | :------------ | :---------- | | GridLabel | `string` | "Data grid" | The grid's accessible name when neither AriaLabel nor AriaLabelledBy is given. | | EmptyText | `string` | BitStrings.NoItemsFound | Shown when there are no rows; "No items found" unless BitStrings.Current says otherwise. | | NoMatchesText | `string` | BitStrings.NoResultsFound | Shown instead of EmptyText when the filters or the search exclude every row; "No results found" unless BitStrings.Current says otherwise. An EmptyTemplate replaces both. | | LoadingText | `string` | "Loading…" | Shown while Loading is true, and while a server grid reads its first rows. | | ReadErrorText | `string` | "The records could not be loaded." | Shown in place of the rows when a read fails and OnReadError is set. | | RetryText | `string` | "Retry" | The button that reads the rows again after a failed read. | | PagerRangeFormat | `string` | "{0}–{1} of {2}" | Pager range summary format. | | PagerPageFormat | `string` | "Page {0} of {1}" | Pager page summary format. | | InvalidValueError | `string` | "Invalid value for {0}." | Shown when an edited value can't be converted. | | SearchPlaceholder | `string` | "Search…" | The quick-search placeholder. | | … | `string` | | Plus 85 more: button texts, labels, placeholders, operator and option texts, tooltips, aggregate formats and live announcements. | ## CSS Variables Public CSS custom properties read off the component's root. Set one on `:root` to restyle every instance, on any ancestor to restyle the ones inside it, or on the `Style` of one instance to restyle it and every instance nested inside it, which inherits the value too - a parameter changes one alone, as does the real CSS property on its `Style` / `Styles` when that property does not inherit (`opacity`); an inherited one (`color`, `font-family`) reaches the nested instances that do not set it themselves. | Name | Default Value | Description | | :--- | :------------ | :---------- | | `--bit-DataGrid-background` | --bit-clr-bg-pri | Background of the grid and its rows. | | `--bit-DataGrid-color` | --bit-clr-fg-pri | Text color. | | `--bit-DataGrid-font-family` | --bit-tpg-font-family | Font of the grid. | | `--bit-DataGrid-font-size` | --bit-tpg-fs-sm | Font size of the grid. | | `--bit-DataGrid-line-height` | 1.4 | Line height of the cells. | | `--bit-DataGrid-border-color` | --bit-clr-brd-ter | Color of the border and of the row and column lines. | | `--bit-DataGrid-border-radius` | --bit-shp-radius-surface | Corner radius of the grid. | | `--bit-DataGrid-cell-padding` | spacing(1) spacing(1.25) | Padding of the cells. | | `--bit-DataGrid-header-background` | --bit-clr-bg-sec | Background of the header rows and the column chooser. | | `--bit-DataGrid-header-color` | The grid's color | Text color of the header rows. | | `--bit-DataGrid-header-font-weight` | --bit-tpg-fw-semibold | Font weight of the column titles. | | `--bit-DataGrid-stripe-background` | --bit-clr-bg-sec | Background of the striped rows. | | `--bit-DataGrid-hover-background` | --bit-clr-bg-pri-hover | Background of the hovered row. | | `--bit-DataGrid-selected-background` | --bit-clr-pri-tint | Wash over a selected row. | | `--bit-DataGrid-selected-color` | The grid's color | Text color of a selected row. | | `--bit-DataGrid-editing-background` | --bit-clr-wrn-tint | Wash over the row (or cell) being edited. | | `--bit-DataGrid-accent-color` | --bit-clr-pri | Sort arrows, badges, group toggle and bar, checkboxes and resize handle. | | `--bit-DataGrid-focus-color` | --bit-clr-pri-focus | Focus indicator of the cells, rows and controls. | | `--bit-DataGrid-group-background` | --bit-clr-bg-ter | Background of the group header rows. | | `--bit-DataGrid-group-indent` | spacing(2.5) | Indent of each group level. | | `--bit-DataGrid-tree-indent` | spacing(2.25) | Indent of each tree level. | | `--bit-DataGrid-detail-background` | --bit-clr-bg-sec | Background of the detail rows. | | `--bit-DataGrid-footer-background` | --bit-clr-bg-sec | Background of the footer row. | | `--bit-DataGrid-disabled-color` | --bit-clr-fg-dis | Text color of a disabled grid. | | `--bit-DataGrid-placeholder-color` | --bit-clr-fg-sec | Placeholder of the search and filter boxes. | ## Examples ## Overview Binding the rows and declaring the columns, sorting, the filter row and paging, quick search, row selection, and keyboard cell navigation with clipboard copy. \n**Basic & sorting**: ```razor ``` ```csharp private readonly List basicProducts = SampleData.Generate(50); public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Filtering & paging**: ```razor ``` ```csharp private readonly List filterProducts = SampleData.Generate(200); private readonly List> categoryFilterItems = Enum.GetNames().Select(name => new BitDropdownItem { Text = name, Value = name }).ToList(); public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Quick search**: ```razor @(string.IsNullOrEmpty(searchTerm) ? "No search term." : $"Searching for \"{searchTerm}\".") ``` ```csharp private readonly List searchProducts = SampleData.Generate(200); private string? searchTerm; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Selection**: ```razor Single Multiple @selectedProducts.Count selected ``` ```csharp private readonly List selectionProducts = SampleData.Generate(60); private BitSelectionMode selectionMode = BitSelectionMode.Multiple; private IReadOnlyList selectedProducts = []; // Switching to Single drops the extra selections, so the bound list matches what the grid can hold. private void SelectSingleMode() { selectionMode = BitSelectionMode.Single; if (selectedProducts.Count > 1) { selectedProducts = selectedProducts.Take(1).ToList(); } } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Keyboard & clipboard**: ```razor Select all Clear selection Copy selection @clipboardStatus ``` ```csharp private readonly List clipboardProducts = SampleData.Generate(40); private BitDataGrid? clipboardGrid; private IReadOnlyList clipboardSelection = []; private string clipboardStatus = "Select rows, then copy them."; private async Task SelectAllRows() { if (clipboardGrid is null) return; await clipboardGrid.SelectAllAsync(); clipboardStatus = $"{clipboardSelection.Count} rows selected."; } private async Task ClearRowSelection() { if (clipboardGrid is null) return; await clipboardGrid.ClearSelectionAsync(); clipboardStatus = "Selection cleared."; } private async Task CopySelection() { if (clipboardGrid is null) return; var copied = await clipboardGrid.CopyToClipboardAsync(); clipboardStatus = copied > 0 ? $"{copied} rows copied to the clipboard." : "Nothing was copied (the clipboard may be unavailable here)."; } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` ## Editing, grouping & templates Inline row and cell editing with validation, grouping with group and footer aggregates, cell, header and footer templates with custom sort keys, and master-detail rows. \n**Inline editing**: ```razor Row Cell @editStatus ``` ```csharp private readonly List editProducts = SampleData.Generate(25); private BitDataGrid? editGrid; private BitDataGridEditMode editMode; private int nextId; private string editStatus = "Double-click a row, or use its Edit button."; protected override void OnInitialized() => nextId = editProducts.Max(p => p.Id) + 1; private Product CreateProduct() => new() { Id = nextId++, Name = "New product", Category = Category.Electronics, Rating = 3, ReleaseDate = DateTime.Today }; private void OnCreate(Product p) => editStatus = $"Adding new product #{p.Id}…"; private void OnSave(Product p) { // The grid hands back an edited copy, so match on the key rather than the reference. var index = editProducts.FindIndex(x => x.Id == p.Id); if (index >= 0) editProducts[index] = p; else editProducts.Insert(0, p); editStatus = $"Saved {p.Name} (#{p.Id})."; } private void OnCancel(Product p) => editStatus = $"Cancelled editing {p.Name}."; private void OnDelete(Product p) { editProducts.RemoveAll(x => x.Id == p.Id); editStatus = $"Deleted #{p.Id}."; } private void EditOnDoubleClick(Product product) { editGrid?.BeginEdit(product); editStatus = $"Editing {product.Name}. Enter saves, Esc cancels."; } // A validator gets the row and the proposed, already converted value; a message rejects it and blocks Save. private string? ValidateName(Product product, object? value) => string.IsNullOrWhiteSpace(value as string) ? "Name is required." : null; private string? ValidatePrice(Product product, object? value) => value is decimal price && price < 0 ? "Price cannot be negative." : null; private string? ValidateStock(Product product, object? value) => value is int stock && stock < 0 ? "Stock cannot be negative." : null; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Grouping & aggregates**: ```razor Expand all groups Collapse all groups ``` ```csharp private readonly List groupProducts = SampleData.Generate(80); private BitDataGrid? groupGrid; // A custom aggregate: gets the rows of a group (or of the whole view for the footer) and returns any value. private object? DistinctSuppliers(IReadOnlyList rows) => $"{rows.Select(p => p.Supplier).Distinct().Count()} distinct"; private async Task ExpandAllGroups() { if (groupGrid is not null) await groupGrid.ExpandAllGroupsAsync(); } private async Task CollapseAllGroups() { if (groupGrid is not null) await groupGrid.CollapseAllGroupsAsync(); } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Templates**: ```razor 📦 Product Total: @agg.FormattedValue ``` ```csharp private readonly List templateProducts = SampleData.Generate(30); // In-stock rows first, then by quantity - an order the raw number cannot express. private readonly IComparer stockComparer = new StockComparer(); private sealed class StockComparer : IComparer { public int Compare(object? x, object? y) { var a = x as int? ?? 0; var b = y as int? ?? 0; var inStock = (a == 0).CompareTo(b == 0); return inStock != 0 ? inStock : a.CompareTo(b); } } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Detail rows**: ```razor Expand all Collapse all @detailStatus ``` ```csharp private readonly List suppliers = BuildSuppliers(); private BitDataGrid? detailGrid; private string detailStatus = "Click a row, or its ▸ toggle, to open it."; private static List BuildSuppliers() => SampleData.Generate(240) .GroupBy(p => p.Supplier) .Select(g => new SupplierModel { Name = g.Key, Products = g.OrderBy(p => p.Name).ToList() }) .OrderBy(s => s.Name) .ToList(); private void OnDetailToggled(BitDataGridDetailEventArgs args) => detailStatus = $"{args.Item.Name} {(args.Expanded ? "expanded" : "collapsed")}."; private async Task ExpandAllDetails() { if (detailGrid is not null) await detailGrid.ExpandAllDetailsAsync(); } private async Task CollapseAllDetails() { if (detailGrid is not null) await detailGrid.CollapseAllDetailsAsync(); } public sealed class SupplierModel { public string Name { get; set; } = ""; public List Products { get; set; } = new(); public int ProductCount => Products.Count; public int TotalStock => Products.Sum(p => p.Stock); public decimal AveragePrice => Products.Count == 0 ? 0 : Math.Round(Products.Average(p => p.Price), 2); } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` ## Columns & styling Resizing, reordering, hiding, freezing and grouping columns, column spans, borders, stripes and row numbers, row and cell styles with tooltips, text wrapping and row height, and the empty and loading states. \n**Column layout**: ```razor ``` ```csharp private readonly List columnsProducts = SampleData.Generate(40); public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Column spanning**: ```razor ``` ```csharp private readonly List spanningProducts = SampleData.Generate(40); private int? NameSpan(Product p) => p.Discontinued ? 2 : null; private int? PriceSpan(Product p) => p.Price > 800 ? 2 : null; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Borders, striping & row numbers**: ```razor Borders: @(bordered ? "on" : "off") Striping: @(striped ? "on" : "off") Hover: @(hoverable ? "on" : "off") Row numbers: @(rowNumbers ? "on" : "off") ``` ```csharp private readonly List borderStripeProducts = SampleData.Generate(60); private bool bordered = true; private bool striped = true; private bool hoverable = true; private bool rowNumbers = true; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Row & cell styling**: ```razor @* The row class lands on an element the grid renders, so the page's scoped CSS needs a plain wrapper of its own to hang ::deep off (see the stylesheet tab). *@
``` ```csharp private readonly List styledRowProducts = SampleData.Generate(60); // Both run per row and come after the grid's own class and style, so they win whatever they repeat. private static string? RowClassFor(Product p) => p.Stock == 0 ? "row-out-of-stock" : null; private static string? RowStyleFor(Product p) => p.Price > 800 ? "font-weight:600;" : null; // Per cell of one column: only the Stock cell of a low-stock row. private static string? StockStyleFor(Product p) => p.Stock is > 0 and < 50 ? "color:var(--bit-clr-wrn-fg);font-weight:600;" : null; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` `Page.razor.css`: ```css /* The class RowClass returns lands on a row the grid renders, not on markup this page wrote, so the page's scope attribute never reaches it. ::deep off the page's own wrapper crosses that boundary. */ .styled-rows ::deep .row-out-of-stock .bit-dtg-cell { color: var(--bit-clr-err-fg); } ``` \n**Text wrapping & row height**: ```razor Wrapping: @(wrapCellText ? "on" : "off") ``` ```csharp private readonly List wrapProducts = SampleData.Generate(40); private bool wrapCellText = true; private static string DescriptionOf(Product p) => $"{p.Name} is a {p.Category.ToString().ToLowerInvariant()} product supplied by {p.Supplier}, " + $"released on {p.ReleaseDate:d} and currently rated {p.Rating:0.0} out of 5 by our customers."; // The minimum height of a row; a wrapped row still grows past it. private static float RowHeightOf(Product p) => p.Price > 800 ? 56f : 36f; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Empty & loading states**: ```razor Clear data Simulate loading Nothing here yet Load sample data ``` ```csharp private readonly List emptyData = SampleData.Generate(25); private readonly List emptyNone = []; private bool emptyHasData; private bool emptyLoading; private List EmptyCurrent => emptyHasData ? emptyData : emptyNone; private async Task SimulateLoading() { emptyLoading = true; StateHasChanged(); await Task.Delay(1500); emptyLoading = false; emptyHasData = true; } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` ## Data & performance The data modes - eager and lazily loaded trees, row and column virtualization, server-side paging with OnRead, infinite scrolling, IQueryable sources - and CSV and Excel export. \n**Tree data**: ```razor Expand all Collapse all ``` ```csharp private readonly List fileRoots = FileSystemData.Build(); private BitDataGrid? treeGrid; private async Task ExpandAll() { if (treeGrid is not null) await treeGrid.ExpandAllAsync(); } private async Task CollapseAll() { if (treeGrid is not null) await treeGrid.CollapseAllAsync(); } private readonly List lazyTreeRoots = [ new() { Id = 1, Name = "src", Kind = "Folder", Modified = new DateTime(2025, 1, 10) }, new() { Id = 2, Name = "docs", Kind = "Folder", Modified = new DateTime(2025, 2, 5) }, new() { Id = 3, Name = "assets", Kind = "Folder", Modified = new DateTime(2025, 3, 20) }, new() { Id = 4, Name = "LICENSE", Kind = "File", Size = 1_070, Modified = new DateTime(2025, 1, 2) }, ]; private int nextLazyNodeId = 1000; // An unloaded node cannot know its children; this decides whether it offers a toggle. private static bool IsFolder(FileNode node) => node.Kind == "Folder"; // Called on a node's first expand only; the grid caches the result. The grid cancels the token // once it no longer needs the children (new Items, or the grid is gone). private async Task?> LoadChildrenAsync(BitDataGridChildrenRequest request) { var parent = request.Parent; await Task.Delay(600, request.CancellationToken); // e.g. await http.GetFromJsonAsync>($"api/files/{parent.Id}", request.CancellationToken) return [ new FileNode { Id = ++nextLazyNodeId, Name = $"{parent.Name}-sub", Kind = "Folder", Modified = parent.Modified.AddDays(1) }, new FileNode { Id = ++nextLazyNodeId, Name = $"{parent.Name}-notes.md", Kind = "File", Size = 2_300, Modified = parent.Modified.AddDays(2) }, new FileNode { Id = ++nextLazyNodeId, Name = $"{parent.Name}-data.json", Kind = "File", Size = 5_100, Modified = parent.Modified.AddDays(3) }, ]; } public class FileNode { public int Id { get; set; } public string Name { get; set; } = ""; public string Kind { get; set; } = "Folder"; public long Size { get; set; } public DateTime Modified { get; set; } public List Children { get; set; } = new(); } public static class FileSystemData { public static List Build() { var id = 0; var baseDate = new DateTime(2025, 1, 1); FileNode Folder(string name, params FileNode[] children) { var node = new FileNode { Id = ++id, Name = name, Kind = "Folder", Modified = baseDate.AddDays(id), Children = children.ToList() }; node.Size = node.Children.Sum(c => c.Size); return node; } FileNode File(string name, long size) => new() { Id = ++id, Name = name, Kind = "File", Size = size, Modified = baseDate.AddDays(id) }; return new List { Folder("src", Folder("BitDataGrid", File("BitDataGrid.razor", 24_500), File("BitDataGrid.razor.cs", 41_200), Folder("Models", File("BitTextAlign.cs", 320), File("BitDataGridSortDescriptor.cs", 540), File("BitDataGridFilterOperator.cs", 610)), Folder("Infrastructure", File("BitDataGridDataProcessor.cs", 8_900), File("BitDataGridPropertyAccessor.cs", 3_400))), Folder("BitDataGrid.Demo", File("Program.cs", 1_200), Folder("Components", File("App.razor", 760), File("Routes.razor", 280)))), Folder("docs", File("README.md", 6_400), File("CHANGELOG.md", 2_100)), Folder("assets", File("logo.svg", 4_800), File("styles.css", 12_300), File("favicon.ico", 1_150)), File("LICENSE", 1_070), File(".gitignore", 410) }; } } ``` \n**Server-side data**: ```razor @serverLastRequest @serverLastError ``` ```csharp private readonly List serverAll = SampleData.Generate(523); private bool serverLoading; private string serverLastRequest = ""; private async Task> LoadServerData(BitDataGridReadRequest request) { serverLoading = true; await InvokeAsync(StateHasChanged); int total = 0; try { await Task.Delay(250, request.CancellationToken); // a backend round trip var filtered = Query(serverAll, request).ToList(); total = filtered.Count; var items = filtered.Skip(request.Skip).Take(request.Take ?? total).ToList(); // A superseded request must not hand back stale rows. request.CancellationToken.ThrowIfCancellationRequested(); return new BitDataGridReadResult(items, total); } finally { // A superseded request leaves the loading state to the newer one. if (!request.CancellationToken.IsCancellationRequested) { serverLastRequest = $"Last request → skip {request.Skip}, take {request.Take}, sorts: {request.Sorts.Count}, filters: {request.Filters.Count}, total: {total}"; serverLoading = false; await InvokeAsync(StateHasChanged); } } } private readonly List serverVirtualAll = SampleData.Generate(100_000); private async Task> LoadVirtualServerData(BitDataGridReadRequest request) { // A scroll window the grid no longer needs is cancelled; let the exception propagate. await Task.Delay(150, request.CancellationToken); var filtered = Query(serverVirtualAll, request).ToList(); var items = filtered.Skip(request.Skip).Take(request.Take ?? filtered.Count).ToList(); // The grid names the aggregates its footer shows (a sum of Price and an average of Rating). Computed over // the WHOLE filtered set, so the footer shows real totals. var aggregates = new List(); foreach (var aggregate in request.Aggregates) { if (aggregate is { ColumnId: nameof(Product.Price), Type: BitDataGridAggregateType.Sum }) { var sum = filtered.Sum(p => p.Price); aggregates.Add(new() { ColumnId = aggregate.ColumnId, Type = aggregate.Type, Value = sum, FormattedValue = sum.ToString("C0") }); } else if (aggregate is { ColumnId: nameof(Product.Rating), Type: BitDataGridAggregateType.Average }) { var average = filtered.Count == 0 ? 0 : filtered.Average(p => p.Rating); aggregates.Add(new() { ColumnId = aggregate.ColumnId, Type = aggregate.Type, Value = average, FormattedValue = average.ToString("N1") }); } } return new BitDataGridReadResult(items, filtered.Count) { Aggregates = aggregates }; } private bool serverFails; private string serverLastError = ""; private async Task> LoadFlakyServerData(BitDataGridReadRequest request) { await Task.Delay(400, request.CancellationToken); if (serverFails) throw new InvalidOperationException("The server did not answer."); var filtered = Query(serverAll, request).ToList(); return new BitDataGridReadResult(filtered.Skip(request.Skip).Take(request.Take ?? filtered.Count).ToList(), filtered.Count); } // The grid shows its error row and Retry button; this is the place to log the failure or tell the user more. private void HandleReadError(Exception exception) => serverLastError = $"OnReadError: {exception.Message}"; // Applies the request's filters, search and sorts the way a backend would. private static IEnumerable Query(IEnumerable source, BitDataGridReadRequest request) { var query = source; foreach (var f in request.Filters) { query = f.ColumnId switch { nameof(Product.Name) => query.Where(p => MatchText(p.Name, f)), nameof(Product.Supplier) => query.Where(p => MatchText(p.Supplier, f)), nameof(Product.Category) => query.Where(p => MatchComparable(p.Category, f)), nameof(Product.Price) => query.Where(p => MatchComparable(p.Price, f)), nameof(Product.Stock) => query.Where(p => MatchComparable(p.Stock, f)), nameof(Product.Rating) => query.Where(p => MatchComparable(p.Rating, f)), _ => query }; } if (string.IsNullOrWhiteSpace(request.Search) is false) { query = query.Where(p => p.Name.Contains(request.Search, StringComparison.OrdinalIgnoreCase) || p.Supplier.Contains(request.Search, StringComparison.OrdinalIgnoreCase)); } IOrderedEnumerable? ordered = null; foreach (var sort in request.Sorts) { Func key = sort.ColumnId switch { nameof(Product.Name) => p => p.Name, nameof(Product.Category) => p => p.Category, nameof(Product.Supplier) => p => p.Supplier, nameof(Product.Price) => p => p.Price, nameof(Product.Stock) => p => p.Stock, nameof(Product.Rating) => p => p.Rating, _ => p => p.Id }; var descending = sort.Direction == BitDataGridSortDirection.Descending; ordered = ordered is null ? (descending ? query.OrderByDescending(key) : query.OrderBy(key)) : (descending ? ordered.ThenByDescending(key) : ordered.ThenBy(key)); } return ordered ?? query; } // A text filter as the grid's text editor emits it: a string value with one of the string/empty operators. private static bool MatchText(string value, BitDataGridFilterDescriptor f) { if (f.Operator is BitDataGridFilterOperator.IsEmpty) return string.IsNullOrEmpty(value); if (f.Operator is BitDataGridFilterOperator.IsNotEmpty) return !string.IsNullOrEmpty(value); var term = f.Value?.ToString(); if (string.IsNullOrWhiteSpace(term)) return true; return f.Operator switch { BitDataGridFilterOperator.Contains => value.Contains(term, StringComparison.OrdinalIgnoreCase), BitDataGridFilterOperator.DoesNotContain => !value.Contains(term, StringComparison.OrdinalIgnoreCase), BitDataGridFilterOperator.StartsWith => value.StartsWith(term, StringComparison.OrdinalIgnoreCase), BitDataGridFilterOperator.EndsWith => value.EndsWith(term, StringComparison.OrdinalIgnoreCase), BitDataGridFilterOperator.Equals => string.Equals(value, term, StringComparison.OrdinalIgnoreCase), BitDataGridFilterOperator.NotEquals => !string.Equals(value, term, StringComparison.OrdinalIgnoreCase), _ => true }; } // Any other filter arrives as a value of the column's own type with a comparison operator. private static bool MatchComparable(T value, BitDataGridFilterDescriptor f) where T : IComparable { if (f.Operator is BitDataGridFilterOperator.IsEmpty) return value is null; if (f.Operator is BitDataGridFilterOperator.IsNotEmpty) return value is not null; if (f.Value is not T typed) return true; var cmp = value.CompareTo(typed); return f.Operator switch { BitDataGridFilterOperator.Equals => cmp == 0, BitDataGridFilterOperator.NotEquals => cmp != 0, BitDataGridFilterOperator.GreaterThan => cmp > 0, BitDataGridFilterOperator.GreaterThanOrEqual => cmp >= 0, BitDataGridFilterOperator.LessThan => cmp < 0, BitDataGridFilterOperator.LessThanOrEqual => cmp <= 0, _ => true }; } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Infinite scrolling**: ```razor @infiniteLog ``` ```csharp private readonly List infiniteAll = SampleData.Generate(2_017); private string infiniteLog = "Scroll down to load more…"; private int infiniteRequests; private async Task> LoadMore(BitDataGridReadRequest request) { await Task.Delay(350, request.CancellationToken); // a backend round trip // Take is the batch size while scrolling; null means "every row" (an export). var batch = Query(infiniteAll, request).Skip(request.Skip).Take(request.Take ?? infiniteAll.Count).ToList(); request.CancellationToken.ThrowIfCancellationRequested(); infiniteRequests++; infiniteLog = batch.Count == 0 ? $"Batch #{infiniteRequests} → no more rows" : $"Batch #{infiniteRequests} → rows {request.Skip + 1}–{request.Skip + batch.Count}"; await InvokeAsync(StateHasChanged); // There is no known total in this mode; a batch shorter than requested ends the list. return new BitDataGridReadResult(batch, 0); } // Query applies request.Sorts and request.Filters - see the Server-side data example. public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**IQueryable data source**: ```razor ``` ```csharp // Any IQueryable works; with EF Core this is simply: private IQueryable queryableProducts => db.Products; private readonly IQueryable queryableProducts = SampleData.Generate(400).AsQueryable(); public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Export**: ```razor ``` ```csharp private readonly List exportProducts = SampleData.Generate(30); // A merged cell in Excel; CSV has no merges and writes every column's own value. private int? NameSpan(Product p) => p.Discontinued ? 2 : null; // The same exports from code (all return or download every matching row): // string csv = await grid.ToCsvAsync(); // byte[] xlsx = await grid.ToExcelAsync(selectedOnly: true); public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` ## Interaction & state Dragging rows into a new order, row and cell events with a custom context menu, the programmatic API and its change events, and saving and restoring the grid's state. \n**Row reordering**: ```razor @reorderLog ``` ```csharp private readonly List reorderProducts = SampleData.Generate(12); private string? reorderLog; private void OnReorder(BitDataGridRowReorderEventArgs e) { // FromIndex/ToIndex are null when the bound Items isn't an indexable IList. var from = e.FromIndex is int fi ? (fi + 1).ToString() : "?"; var to = e.ToIndex is int ti ? (ti + 1).ToString() : "?"; reorderLog = $"{e.DraggedItem.Name} moved from #{from} to #{to}"; } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Cell events & context menu**: ```razor @cellEventStatus @if (cellMenuArgs is not null) {
} ``` ```csharp private readonly List cellEventsProducts = SampleData.Generate(40); private string cellEventStatus = "Click, double-click or right-click any cell."; private BitDataGrid? cellEventsGrid; private BitDataGridCellEventArgs? cellMenuArgs; private int cellMenuX; private int cellMenuY; private ElementReference cellMenuFirstItem; private bool cellMenuFocusPending; private void OnCellClick(BitDataGridCellEventArgs e) => cellEventStatus = $"Clicked {e.ColumnTitle} = \"{e.Value}\" on {e.Item.Name}"; private void OnCellDoubleClick(BitDataGridCellEventArgs e) => cellEventStatus = $"Double-clicked {e.ColumnTitle} on {e.Item.Name}"; private void OnCellContextMenu(BitDataGridCellEventArgs e) { cellMenuArgs = e; // ClientX/Y are viewport coordinates, matching the menu's position:fixed placement. cellMenuX = (int)e.Mouse.ClientX; cellMenuY = (int)e.Mouse.ClientY; cellEventStatus = $"Right-clicked {e.ColumnTitle} on {e.Item.Name}"; cellMenuFocusPending = true; } private void CloseCellMenu() => cellMenuArgs = null; private void OnCellMenuKeyDown(KeyboardEventArgs e) { if (e.Key == "Escape") CloseCellMenu(); } protected override async Task OnAfterRenderAsync(bool firstRender) { // Move the focus into the menu once it renders, so the keyboard can operate and dismiss it. if (cellMenuFocusPending && cellMenuArgs is not null) { cellMenuFocusPending = false; await cellMenuFirstItem.FocusAsync(); } } private async Task CopyCellValue() { if (cellMenuArgs is null) return; await JSRuntime.InvokeVoidAsync("navigator.clipboard.writeText", cellMenuArgs.Value?.ToString() ?? ""); cellEventStatus = $"Copied \"{cellMenuArgs.Value}\" to the clipboard."; cellMenuArgs = null; } private async Task DeleteCellMenuRow() { if (cellMenuArgs is null) return; cellEventsProducts.Remove(cellMenuArgs.Item); cellEventStatus = $"Deleted {cellMenuArgs.Item.Name}."; cellMenuArgs = null; // The grid caches its processed view; a list changed in place needs an explicit refresh. if (cellEventsGrid is not null) await cellEventsGrid.RefreshAsync(); } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` `Page.razor.css`: ```css /* The invisible overlay catches the click or right-click that dismisses the menu. */ .ctx-menu-overlay { position: fixed; inset: 0; z-index: 999; } .ctx-menu { position: fixed; z-index: 1000; min-width: 180px; padding: 4px; display: flex; flex-direction: column; background: var(--bit-clr-bg-pri); border: 1px solid var(--bit-clr-brd-ter); border-radius: var(--bit-shp-radius-popup); box-shadow: var(--bit-shd-popup); } .ctx-menu-header { padding: 6px 10px; margin-bottom: 4px; font-size: 0.75rem; color: var(--bit-clr-fg-sec); border-bottom: 1px solid var(--bit-clr-brd-ter); white-space: nowrap; } .ctx-menu-item { padding: 6px 10px; border: none; border-radius: 4px; background: none; color: var(--bit-clr-fg-pri); font: inherit; text-align: start; cursor: pointer; } .ctx-menu-item:hover, .ctx-menu-item:focus-visible { background: var(--bit-clr-bg-pri-hover); } .ctx-menu-danger { color: var(--bit-clr-err-fg); } ``` \n**Programmatic control**: ```razor Sort by price ↓ Clear sorts Filter price > 500 Clear filters Group by category Ungroup Go to page 3 Page size 50 Move Price first Reveal a random row Refresh @apiLog @apiViewLog ``` ```csharp private readonly List apiProducts = SampleData.Generate(200); private BitDataGrid? apiGrid; private string apiLog = "The grid reports every view change here."; private IReadOnlyList apiViewItems = []; private string apiViewLog = ""; private async Task ApiSortByPrice() { if (apiGrid is not null) await apiGrid.SortByAsync(nameof(Product.Price), BitDataGridSortDirection.Descending); } private async Task ApiClearSorts() { if (apiGrid is not null) await apiGrid.ClearSortsAsync(); } private async Task ApiFilterExpensive() { if (apiGrid is not null) await apiGrid.ApplyFilterAsync(nameof(Product.Price), BitDataGridFilterOperator.GreaterThan, 500m); } private async Task ApiClearFilters() { if (apiGrid is not null) await apiGrid.ClearFiltersAsync(); } private async Task ApiGroupByCategory() { if (apiGrid is not null) await apiGrid.GroupByAsync(nameof(Product.Category)); } private async Task ApiUngroup() { if (apiGrid is not null) await apiGrid.UngroupAsync(nameof(Product.Category)); } private async Task ApiGoToPage3() { if (apiGrid is not null) await apiGrid.GoToPageAsync(3); } private async Task ApiPageSize50() { if (apiGrid is not null) await apiGrid.SetPageSizeAsync(50); } private async Task ApiPriceFirst() { if (apiGrid is not null) await apiGrid.MoveColumnAsync(nameof(Product.Price), 0); } private async Task ApiRefresh() { if (apiGrid is not null) await apiGrid.RefreshAsync(); } private async Task ApiRevealRandom() { if (apiGrid is null || apiViewItems.Count == 0) return; var product = apiViewItems[Random.Shared.Next(apiViewItems.Count)]; if (await apiGrid.RevealItemAsync(product)) apiLog = $"Revealed {product.Name} (#{product.Id}) on page {apiGrid.CurrentPage}."; } private void OnApiViewChange(IReadOnlyList rows) { apiViewItems = rows; apiViewLog = $"{rows.Count} row(s) in the view, from {rows.FirstOrDefault()?.Name ?? "-"} to {rows.LastOrDefault()?.Name ?? "-"}."; } private void OnApiSortChange(IReadOnlyList sorts) => apiLog = sorts.Count == 0 ? "Sorting cleared." : $"Sorting by {string.Join(", ", sorts.Select(s => $"{s.ColumnId} {s.Direction}"))}."; private void OnApiFilterChange(IReadOnlyList filters) => apiLog = filters.Count == 0 ? "Filters cleared." : $"{filters.Count} filter(s) active."; private void OnApiGroupChange(IReadOnlyList groups) => apiLog = groups.Count == 0 ? "Grouping cleared." : $"Grouped by {string.Join(" › ", groups.Select(g => g.ColumnId))}."; private void OnApiPageChange(int page) => apiLog = $"Moved to page {page}."; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**State persistence**: ```razor Recreate & restore Recreate fresh @gridStateStatus ``` ```csharp private readonly List stateProducts = SampleData.Generate(120); private BitDataGrid? stateGrid; private BitDataGridState? savedGridState; private int stateGridKey; private bool stateRestorePending; private string gridStateStatus = "Sort, filter, resize, move or hide columns - every change is saved."; // A real app would serialize the snapshot to local storage or a user-preferences store here. private void SaveGridState(BitDataGridState state) { savedGridState = state; gridStateStatus = $"Saved: page {state.CurrentPage}, {state.Sorts.Count} sort(s), {state.Filters.Count} filter(s)."; } // A new key mounts a brand-new grid, the way a page reload would. private void RecreateGrid(bool restore) { stateGridKey++; stateRestorePending = restore && savedGridState is not null; gridStateStatus = stateRestorePending ? "Recreated and restored." : "Recreated with its defaults."; } protected override async Task OnAfterRenderAsync(bool firstRender) { // The new grid has rendered and its columns have registered, so the snapshot can be applied. if (stateRestorePending && stateGrid is not null && savedGridState is not null) { stateRestorePending = false; await stateGrid.ApplyStateAsync(savedGridState); } } public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` ## Localization & appearance Translating the grid's texts and its values, the disabled grid, app-wide defaults through BitParams, the pager and toolbar layout, Style & Class with the CSS variables, and right-to-left grids. \n**Localization**: ```razor ``` ```csharp private readonly List localizedProducts = SampleData.Generate(60); // Every string has an English default; override what you need. private readonly BitDataGridStrings germanStrings = new() { GridLabel = "Produkte", EmptyText = "Keine Einträge vorhanden.", LoadingText = "Wird geladen…", SearchPlaceholder = "Suchen…", SearchLabel = "Alle Spalten durchsuchen", ClearSearchLabel = "Suche löschen", FilterPlaceholder = "Filtern…", FilterByFormat = "Nach {0} filtern", FilterAllText = "Alle", ClearFiltersText = "Filter löschen", PagerRangeFormat = "{0}–{1} von {2}", PagerPageFormat = "Seite {0} von {1}", PerPageFormat = "{0} pro Seite", RowsPerPageLabel = "Zeilen pro Seite", FirstPageLabel = "Erste Seite", PreviousPageLabel = "Vorherige Seite", NextPageLabel = "Nächste Seite", LastPageLabel = "Letzte Seite", AnnouncementSortedAscending = "Nach {0} aufsteigend sortiert", AnnouncementSortedDescending = "Nach {0} absteigend sortiert", AnnouncementSortCleared = "Sortierung nach {0} entfernt", AnnouncementPage = "Seite {0} von {1}", }; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Disabled**: ```razor ``` ```csharp private readonly List disabledProducts = SampleData.Generate(40); private bool gridDisabled = true; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Cascading parameters**: ```razor ``` ```csharp private readonly List cascadingProducts = SampleData.Generate(30); private readonly BitDataGridParams[] dataGridParams = [ new() { Striped = false, ShowRowNumbers = true, Pageable = true, PageSize = 5, PageSizeOptions = [5, 10], Filterable = true, } ]; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Value text**: ```razor ``` ```csharp private readonly List valueTextProducts = SampleData.Generate(60); // Handed a non-null value of the column; null keeps the default text (the member's own name here). private static string? CategoryText(object value) => value switch { Category.Electronics => "Electronics & gadgets", Category.Home => "Home & garden", Category.Sports => "Sports & outdoors", Category.Grocery => "Food & grocery", _ => null }; private static string? StatusText(object value) => value is true ? "Discontinued" : "In catalog"; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Pager & toolbar**: ```razor Pager on top At the bottom Both Header: @(pagerShowHeader ? "on" : "off") ``` ```csharp private readonly List pagerProducts = SampleData.Generate(120); // The PageSize in effect (15) is added to the options when it is not one of them. private readonly int[] pagerSizeOptions = [10, 25, 50]; private BitPlacement pagerPlacement = BitPlacement.TopAndBottom; private bool pagerShowHeader = true; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` \n**Style & Class**: ```razor
``` ```csharp private readonly List styleProducts = SampleData.Generate(20); private IReadOnlyList styleSelection = []; public enum Category { Electronics, Books, Clothing, Home, Toys, Sports, Grocery } public class Product { public int Id { get; set; } public string Name { get; set; } = ""; public Category Category { get; set; } public decimal Price { get; set; } public int Stock { get; set; } public double Rating { get; set; } public bool Discontinued { get; set; } public DateTime ReleaseDate { get; set; } public string Supplier { get; set; } = ""; } // Deterministic generator so the demo data is reproducible. public static class SampleData { static readonly string[] Adjectives = { "Ultra", "Premium", "Eco", "Smart", "Classic", "Pro", "Mini", "Mega", "Vintage", "Modern", "Deluxe", "Compact" }; static readonly string[] Nouns = { "Widget", "Gadget", "Speaker", "Notebook", "Jacket", "Lamp", "Blender", "Drone", "Backpack", "Sneaker", "Camera", "Mug" }; static readonly string[] Suppliers = { "Acme Corp", "Globex", "Initech", "Umbrella", "Soylent", "Stark Industries", "Wayne Enterprises", "Wonka Inc" }; public static List Generate(int count, int seed = 42) { var rng = new Random(seed); var categories = Enum.GetValues(); var list = new List(count); var referenceDate = new DateTime(2024, 1, 1); for (int i = 1; i <= count; i++) { list.Add(new Product { Id = i, Name = $"{Adjectives[rng.Next(Adjectives.Length)]} {Nouns[rng.Next(Nouns.Length)]} {rng.Next(100, 999)}", Category = categories[rng.Next(categories.Length)], Price = Math.Round((decimal)(rng.NextDouble() * 990 + 5), 2), Stock = rng.Next(0, 500), Rating = Math.Round(rng.NextDouble() * 4 + 1, 1), Discontinued = rng.Next(0, 5) == 0, ReleaseDate = referenceDate.AddDays(-rng.Next(0, 2000)), Supplier = Suppliers[rng.Next(Suppliers.Length)] }); } return list; } } ``` `Page.razor.css`: ```css /* Classes puts these on parts the grid renders, so they are reached through ::deep off a wrapper the page owns. */ .styled-grid ::deep .custom-header-cell { color: var(--bit-clr-pri); text-transform: uppercase; letter-spacing: 0.04em; } .styled-grid ::deep .custom-selected-row .bit-dtg-cell { font-style: italic; } ```