Class TwDataTable<TItem>
- Namespace
- TwBlazor.Components
- Assembly
- TwBlazor.dll
Represents a generic data table component for displaying and managing a collection of items with features such as search, pagination, and customizable rendering.
public class TwDataTable<TItem> : TwBlazorComponentBase, IComponent, IHandleEvent, IHandleAfterRender, ITwComponent, IAsyncDisposable
Type Parameters
TItemThe type of items displayed in the table.
- Inheritance
-
TwDataTable<TItem>
- Implements
- Inherited Members
Remarks
This component allows for flexible rendering of table headers and rows, supports pagination, and provides options for styling and behavior customization. It is designed to work seamlessly with Blazor components.
Constructors
TwDataTable()
public TwDataTable()
Properties
BodyClass
Additional CSS classes for the table body.
[Parameter]
public string? BodyClass { get; set; }
Property Value
Bordered
Whether to show borders.
[Parameter]
public bool Bordered { get; set; }
Property Value
CanEditRow
Gets or sets which rows can be edited, or null for every row. Rows it returns false for get no
Edit button.
[Parameter]
public Func<TItem, bool>? CanEditRow { get; set; }
Property Value
Caption
Optional caption content for the table, forwarded to the underlying TwTable. Provides an
accessible name/description for the table that is programmatically associated with it via
<caption>. Visually hidden by default unless CaptionVisible is true.
[Parameter]
public RenderFragment? Caption { get; set; }
Property Value
CaptionVisible
Whether the Caption should be visible. Defaults to false, rendering the caption
visually hidden (but still available to assistive technology).
[Parameter]
public bool CaptionVisible { get; set; }
Property Value
ColumnGroup
Optional column definitions for a manually defined table (TableHeader and TableRow), passed to ColumnGroup. Use TwTableColumn to set column widths. When Columns is used, set Width on each column instead.
[Parameter]
public RenderFragment? ColumnGroup { get; set; }
Property Value
ColumnMenu
Whether each column header has an options button that opens a TwMenu for sorting, grouping,
moving and hiding the column, showing any hidden column again, and resetting the columns. Only applies when
Columns is used. Defaults to false.
[Parameter]
public bool ColumnMenu { get; set; }
Property Value
Columns
Defines the columns for the table. When provided, headers will be auto-generated with sorting support. Leave null to use manual TableHeader and TableRow fragments.
[Parameter]
public List<TwDataTableColumn<TItem>>? Columns { get; set; }
Property Value
- List<TwDataTableColumn<TItem>>
ComfortablePagination
Whether to render the pagination controls with more comfortable, regular-size buttons instead of the default dense (smaller, more
compact) buttons. Defaults to false. Only applies when EnablePagination is true.
[Parameter]
public bool ComfortablePagination { get; set; }
Property Value
DefineTableRows
If true, manually define <tr> elements in TableRow. Otherwise, they are auto-generated.
[Parameter]
public bool DefineTableRows { get; set; }
Property Value
Editable
Whether rows can be edited in place. Adds an Actions column with an Edit button on each row, which turns the
row's Editable cells into editors with Save and Cancel buttons. Only
applies when Columns is used. Defaults to false.
[Parameter]
public bool Editable { get; set; }
Property Value
EmptyContent
Content to display when there are no items.
[Parameter]
public RenderFragment? EmptyContent { get; set; }
Property Value
EnablePagination
Whether the rows are split into pages, with a pagination below the table (EnablePagination).
Defaults to true. Ignored while EnableVirtualization is set.
[Parameter]
public bool EnablePagination { get; set; }
Property Value
EnableVirtualization
Whether to render only the rows scrolled into view, so a table of thousands of rows stays fast
(EnableVirtualization). The rows scroll inside the table, which is Height
tall, and the pagination is replaced by scrolling. Defaults to false.
[Parameter]
public bool EnableVirtualization { get; set; }
Property Value
Remarks
Every row should be about ItemSize pixels tall, so keep cell content to one line. With Columns the table tells assistive technology how many rows it has and where each rendered row sits, so a screen reader still reads "row 5000 of 10000".
ExportFileName
Gets or sets the name of the downloaded file, without its extension. It also names the Excel worksheet.
Defaults to export.
[Parameter]
public string ExportFileName { get; set; }
Property Value
ExportFormats
Gets or sets which file formats get an export button. Defaults to All.
[Parameter]
public TwDataTableExportFormats ExportFormats { get; set; }
Property Value
ExportScope
Gets or sets which rows the export buttons include. Defaults to Filtered: every row that matches the search, in the order it is sorted.
[Parameter]
public TwDataTableExportScope ExportScope { get; set; }
Property Value
Exportable
Whether to show buttons that download the table as a file. Only applies when Columns is
used. Defaults to false.
[Parameter]
public bool Exportable { get; set; }
Property Value
FixedLayout
Whether column widths come from the column definitions and header row instead of the cell content
(FixedLayout). Columns then keep the same width as the rows change from page to page,
or as a search filters them. Defaults to false.
[Parameter]
public bool FixedLayout { get; set; }
Property Value
GroupBy
Gets or sets the Name of the column to group the rows by when the table first renders. The column needs Groupable set. People can change the grouping from the Group by list, which appears once any column is groupable.
[Parameter]
public string? GroupBy { get; set; }
Property Value
GroupByLabel
Gets or sets the label of the Group by list. Defaults to the localized DataTable_GroupBy text ("Group by").
[Parameter]
public string? GroupByLabel { get; set; }
Property Value
GroupHeaderTemplate
Gets or sets extra content for each group header, shown after the group's name and row count, such as a total. The context is the TwDataTableGroup<TItem>.
[Parameter]
public RenderFragment<TwDataTableGroup<TItem>>? GroupHeaderTemplate { get; set; }
Property Value
- RenderFragment<TwDataTableGroup<TItem>>
HeaderClass
Additional CSS classes for the table header.
[Parameter]
public string? HeaderClass { get; set; }
Property Value
HeaderRowClass
Additional CSS classes for the header row (tr element) when using Columns. Applied on top of the shared Header theme token, so customizing that theme property affects this header row too.
[Parameter]
public string? HeaderRowClass { get; set; }
Property Value
Height
Gets or sets the tallest the table can grow before its rows scroll inside it, as any CSS length. Defaults to
32rem when EnableVirtualization is set, and to no limit otherwise.
[Parameter]
public string? Height { get; set; }
Property Value
Hoverable
Whether to show hover effect on rows.
[Parameter]
public bool Hoverable { get; set; }
Property Value
ItemSize
Gets or sets the height of a row in pixels when EnableVirtualization is set, used to work out
which rows are in view before they render. Defaults to 41, the height of a row in the default theme.
[Parameter]
public float ItemSize { get; set; }
Property Value
Items
The data items to display in the table.
[Parameter]
public List<TItem> Items { get; set; }
Property Value
- List<TItem>
ItemsChanged
Event callback when Items parameter changes.
[Parameter]
public EventCallback<List<TItem>> ItemsChanged { get; set; }
Property Value
- EventCallback<List<TItem>>
ItemsProvider
Gets or sets a function that loads rows on demand, such as from a database or an API, in place of Items. The table passes it the page, sort, search and column filters, so the work happens where the data lives. Grouping is not available, and an export of every row asks the function for all of them.
[Parameter]
public TwDataTableItemsProvider<TItem>? ItemsProvider { get; set; }
Property Value
- TwDataTableItemsProvider<TItem>
LoadingContent
Gets or sets what to show while ItemsProvider loads the first rows. Defaults to the localized DataTable_Loading text ("Loading…").
[Parameter]
public RenderFragment? LoadingContent { get; set; }
Property Value
OverscanCount
Gets or sets how many extra rows to render above and below the ones in view when
EnableVirtualization is set, so fast scrolling does not show gaps. Defaults to 5.
[Parameter]
public int OverscanCount { get; set; }
Property Value
ResizableColumns
Whether people can resize the columns by dragging the border at the end of a column's header, or by focusing
that border and pressing the arrow keys (ResizableColumns). Only applies when
Columns is used. Defaults to false.
[Parameter]
public bool ResizableColumns { get; set; }
Property Value
RowClass
Additional CSS classes for table rows.
[Parameter]
public string? RowClass { get; set; }
Property Value
RowEditCancelled
Raised when a person cancels editing a row. The row is left as it was.
[Parameter]
public EventCallback<TItem> RowEditCancelled { get; set; }
Property Value
- EventCallback<TItem>
RowLabel
Gets or sets how a row is named in the Edit, Save and Cancel buttons' accessible names, such as "Edit Kettle". Defaults to the text of the first visible column.
[Parameter]
public Func<TItem, string>? RowLabel { get; set; }
Property Value
RowSaved
Raised after a person saves an edited row. Every column with a ValueSetter has already written its value to the row, so this is the place to save the row to a database or API.
[Parameter]
public EventCallback<TwDataTableRowEdit<TItem>> RowSaved { get; set; }
Property Value
- EventCallback<TwDataTableRowEdit<TItem>>
RowsPerPage
Number of rows per page.
[Parameter]
public int RowsPerPage { get; set; }
Property Value
RowsPerPageChanged
Event callback when RowsPerPage parameter changes.
[Parameter]
public EventCallback<int> RowsPerPageChanged { get; set; }
Property Value
RowsPerPageOptions
Options for rows per page dropdown.
[Parameter]
public int[] RowsPerPageOptions { get; set; }
Property Value
- int[]
SearchLabel
Label for the search field. Defaults to the localized DataTable_SearchLabel text ("Search").
[Parameter]
public string? SearchLabel { get; set; }
Property Value
SearchPlaceholder
Placeholder text for the search field. Defaults to the localized DataTable_SearchPlaceholder text ("Search…").
[Parameter]
public string? SearchPlaceholder { get; set; }
Property Value
Searchable
Whether the table has search functionality.
[Parameter]
public bool Searchable { get; set; }
Property Value
State
Gets or sets the table's state: its sort, search, page, page size and columns. Bind it with
@bind-State to keep a copy that follows every change, then save that copy wherever suits you and pass
it back later to restore the table. When it is null the table starts from its parameters.
[Parameter]
public TwDataTableState? State { get; set; }
Property Value
StateChanged
Raised with a new TwDataTableState each time a person sorts, searches, changes page or page size, or changes the columns.
[Parameter]
public EventCallback<TwDataTableState> StateChanged { get; set; }
Property Value
StateStorageKey
Gets or sets a key to save the table's state under in the browser's local storage. The table then comes
back the way the person left it on their next visit. Use a key that is unique to the table, such as
"orders-table". Ignored while State is set, so state you manage yourself always wins.
[Parameter]
public string? StateStorageKey { get; set; }
Property Value
Remarks
Local storage can only be read once the page is interactive, so the saved state is applied just after the first render.
StickyHeader
Whether the header row stays in view while the rows scroll. Always on when
EnableVirtualization is set. Defaults to false.
[Parameter]
public bool StickyHeader { get; set; }
Property Value
Striped
Whether to show striped rows.
[Parameter]
public bool Striped { get; set; }
Property Value
TableAttributes
Additional attributes for the table element.
[Parameter]
public Dictionary<string, object> TableAttributes { get; set; }
Property Value
TableClass
Additional CSS classes for the table element itself.
[Parameter]
public string? TableClass { get; set; }
Property Value
TableHeader
RenderFragment for table header cells.
[Parameter]
public RenderFragment? TableHeader { get; set; }
Property Value
TableRow
RenderFragment for table row cells, receives the row item.
[Parameter]
public RenderFragment<TItem>? TableRow { get; set; }
Property Value
- RenderFragment<TItem>
Methods
BuildRenderTree(RenderTreeBuilder)
Renders the component to the supplied RenderTreeBuilder.
protected override void BuildRenderTree(RenderTreeBuilder __builder)
Parameters
__builderRenderTreeBuilder
CancelEditFromEscapeAsync()
Cancels the edit when a person presses Escape. The row shares the library's Escape order with dialogs and pickers, so a date picker or list opened from the row closes first and the next press cancels the edit.
[JSInvokable("CloseFromEscape")]
public Task CancelEditFromEscapeAsync()
Returns
- Task
A task that completes once the edit is cancelled.
CloseFilterAsync()
Closes the open column filter without changing it, and returns focus to its button. The Escape key and a click outside the filter call this too.
[JSInvokable("Close")]
public Task CloseFilterAsync()
Returns
- Task
A task that completes once the filter is closed.
DisposeAsync()
Removes the listeners the table registered for an open filter or an edited row, and releases the reference the scripts held to it.
public ValueTask DisposeAsync()
Returns
- ValueTask
A task that completes once the table is cleaned up.
ExportCsvAsync(TwDataTableExportScope?)
Downloads the table's rows as a CSV file named after ExportFileName.
public Task ExportCsvAsync(TwDataTableExportScope? scope = null)
Parameters
scopeTwDataTableExportScope?Which rows to download, or
nullfor ExportScope.
Returns
- Task
A task that completes once the download has been handed to the browser.
ExportExcelAsync(TwDataTableExportScope?)
Downloads the table's rows as an Excel workbook named after ExportFileName.
public Task ExportExcelAsync(TwDataTableExportScope? scope = null)
Parameters
scopeTwDataTableExportScope?Which rows to download, or
nullfor ExportScope.
Returns
- Task
A task that completes once the download has been handed to the browser.
GetCsv(TwDataTableExportScope?)
Writes the table's rows as CSV text. The columns are the ones on screen, in the order they are shown,
leaving out any column whose Exportable is false. With an
ItemsProvider it writes the rows already loaded; ExportCsvAsync(TwDataTableExportScope?) loads the rest.
public string GetCsv(TwDataTableExportScope? scope = null)
Parameters
scopeTwDataTableExportScope?Which rows to write, or
nullfor ExportScope.
Returns
- string
The CSV text.
GetExcel(TwDataTableExportScope?)
Writes the table's rows as an Excel workbook, with the same columns as GetCsv(TwDataTableExportScope?).
public byte[] GetExcel(TwDataTableExportScope? scope = null)
Parameters
scopeTwDataTableExportScope?Which rows to write, or
nullfor ExportScope.
Returns
- byte[]
The contents of an
.xlsxfile.
GetState()
Gets a snapshot of the table's current state. Changing the snapshot does not change the table; pass it to SetStateAsync(TwDataTableState) to do that.
public TwDataTableState GetState()
Returns
- TwDataTableState
A new TwDataTableState.
OnAfterRenderAsync(bool)
Method invoked after each time the component has been rendered interactively and the UI has finished updating (for example, after elements have been added to the browser DOM). Any ElementReference fields will be populated by the time this runs.
This method is not invoked during prerendering or server-side rendering, because those processes are not attached to any live browser DOM and are already complete before the DOM is updated.
Note that the component does not automatically re-render after the completion of any returned Task, because that would cause an infinite render loop.
protected override Task OnAfterRenderAsync(bool firstRender)
Parameters
firstRenderboolSet to
trueif this is the first time OnAfterRender(bool) has been invoked on this component instance; otherwisefalse.
Returns
Remarks
The OnAfterRender(bool) and OnAfterRenderAsync(bool) lifecycle methods
are useful for performing interop, or interacting with values received from @ref.
Use the firstRender parameter to ensure that initialization work is only performed
once.
OnParametersSet()
Invoked when the component's parameters have been set. Ensures that the component has a unique identifier by generating one if none is provided.
protected override void OnParametersSet()
Remarks
If the component's identifier is not set, a unique ID is generated based on the component's type name (with a 'Tw' prefix removed if present) and a GUID. This helps ensure that each component instance can be uniquely identified, which is useful for scenarios such as associating labels with form elements or targeting elements in client-side scripts.
RefreshDataAsync()
Asks ItemsProvider for the rows again, keeping the page, sort, search and filters. Call it after the data changes somewhere the table cannot see. Without a provider, shows Items again.
public Task RefreshDataAsync()
Returns
- Task
A task that completes once the rows are loaded.
ResetStateAsync()
Puts the sort, search, page, page size, columns and grouping back to how the parameters define them, and saves that under StateStorageKey in place of what was there.
public Task ResetStateAsync()
Returns
- Task
A task that completes once the table is reset.
SetStateAsync(TwDataTableState)
Restores the table to state, saves it when StateStorageKey is set and raises
StateChanged.
public Task SetStateAsync(TwDataTableState state)
Parameters
stateTwDataTableStateThe state to restore. Columns and sorts the table does not have are ignored.
Returns
- Task
A task that completes once the state is applied.