# Blazor Tree Grid (TreeList)

URL: https://flexcoreui.com/demo/grid/tree-grid  
Section: Data Grid  
Controls: TreeGridControl, TreeGridColumn  
Keywords: tree grid, treegrid, treelist, hierarchical grid, self-referencing hierarchy, lazy loading

Show parent-child data in a Blazor tree grid: collapsible rows built from Id and ParentId, 4,009 airports loaded on demand, and an org chart.

## Documentation

### Data

| Name | Type | Default | Description |
|---|---|---|---|
| DataSource | IEnumerable<TValue>? | null | The flat list of rows. The hierarchy is rebuilt when a different list instance is assigned, not when the same list is mutated; both examples build a new list and remount with @key. Keys must be non-null and unique and parent links acyclic, or an ArgumentException is thrown. |
| ChildContent | RenderFragment? | null | The TreeGridColumn declarations. They render into a hidden element and register themselves with the control, which draws from that list. |
| IdMapping | string | "" | Name of the public property that holds each row's key, read by reflection. Empty builds no rows; a name that is not a property throws. |
| ParentIdMapping | string | "" | Name of the property that holds the parent's key. Null, or a key no row has, makes the row a root. |
| TreatAsParent | Func<TValue, bool>? | null | Marks a row expandable although no child is in the list, until a LoadChildren call for it has completed. Without LoadChildren such a row only gains the icon and the Expanded / Collapsed events; the first example passes it for rows that already have children. |
| LoadChildren | Func<TValue, CancellationToken, Task<IReadOnlyList<TValue>>>? | null | Lazy loading: called the first time a TreatAsParent row opens, with the row and a token canceled on dispose, and must return that row's direct children (parent key equal to its key, else ArgumentException). The children join the tree and stay until a new DataSource instance arrives; a failure raises LoadFailed. |
| TreeColumnIndex | int | 0 | Index, in the declared column list, of the column that carries the indent, the expand icon and the folder icon. A hidden column there falls back to the same index among the visible columns. |

### Expansion

| Name | Type | Default | Description |
|---|---|---|---|
| EnableCollapseAll | bool | false | False builds every parent open, true every parent closed. Ignored when InitialExpansionPredicate is set: the org chart sets both and the predicate wins. |
| InitialExpansionPredicate | Func<TValue, bool>? | null | Decides each parent's state when the tree is built: true open, false closed. Set, it replaces EnableCollapseAll. It runs again on every rebuild; PreserveExpansionOnDataChange then restores the states kept from the previous list. |
| PreserveExpansionOnDataChange | bool | true | When a new list arrives, parents keep the state they had under the previous list, matched by key; new keys take their initial state. False gives every parent its initial state. |
| ToggleOnRowClick | bool | true | A click anywhere on a parent row toggles it as well as selecting it. False leaves toggling to the icon, the keyboard and the methods; both examples turn it off. |
| SpaceTogglesExpansion | bool | true | Space on the selected parent toggles it. False frees Space for OnHostKeyDown. With ShowCheckboxes, Space toggles the row's checkbox and never reaches this. |

### Icons

| Name | Type | Default | Description |
|---|---|---|---|
| IndentPerLevel | int | 16 | Pixels of indent per level in the tree column, before the icon. With fx-treegrid-dotted-lines in CssClass each level is drawn as a connector segment of this width. |
| NodeExpandIconStyle | GroupExpandIconStyle | GroupExpandIconStyle.PlusMinus | PlusMinus: a bordered + or − box, leaf rows getting a blank placeholder of the same width. Triangle: a folder image in place of the box (closed, or open with ChangeNodeIconOnExpand); its ▶ / ▼ glyphs appear only once CollapsedGlyph or ExpandedGlyph moves the row onto the glyph path. |
| CollapsedGlyph | string? | null | Glyph of a closed parent in place of the preset's. Setting it, or ExpandedGlyph, puts a Triangle tree on the glyph path too. |
| ExpandedGlyph | string? | null | Glyph of an open parent in place of the preset's. |
| LeafGlyph | string? | null | Glyph for leaf rows in place of the blank placeholder. |
| ExpandIconStyle | string? | null | Inline style of the parent icon span; null uses the PlusMinus box style, or nothing for Triangle. |
| LeafIconStyle | string? | null | Inline style of the leaf placeholder or glyph span. |
| ExpandIconTemplate | RenderFragment<bool>? | null | Replaces the whole parent icon; receives true when the row shows as open (while a filter is active, that means a child the filter keeps). The template handles the click itself; the control binds none. |
| LeafIconTemplate | RenderFragment? | null | Replaces the leaf placeholder. |
| GetNodeIcon | Func<TValue, bool, string?>? | null | Returns an image URL for a row, or null for none, and is used instead of the folder images; the bool is true only for an open parent with ChangeNodeIconOnExpand. Leaf rows ask it only with ShowLeafNodeIcons. |
| ChangeNodeIconOnExpand | bool | false | Lets the folder image, or GetNodeIcon, switch to the open form while the parent is open. False keeps it stable and leaves the state to the glyph. |
| ShowLeafNodeIcons | bool | true | False drops the folder or GetNodeIcon image on leaf rows; the alignment placeholder stays. Leaves show an image only with GetNodeIcon, a folder class in CssClass or the Triangle preset. |

### Selection

| Name | Type | Default | Description |
|---|---|---|---|
| AllowSelection | bool | true | False: no row is ever selected, so no band is painted, RowSelected never fires and the arrow keys have no current row to move from. Row clicks still toggle parents and raise RowClicked. |
| SelectionMode | SelectionMode | SelectionMode.Row | Row paints the whole row. Cell highlights one cell and Left / Right move that cursor across the columns (on the tree column they still close or open the row); the root gets fx-treegrid-select-cell. One row is selected either way: the tree has no multi-select. |
| RetainFocusOnActivation | bool | true | After Enter raises RowActivated the tree takes focus back. False lets the handler move focus to an editor. |
| TabIndex | int | 0 | tabindex of the root element, the tree's single Tab stop; rows are tabindex -1 and are focused by the keyboard handling. |

### Checking

| Name | Type | Default | Description |
|---|---|---|---|
| ShowCheckboxes | bool | false | Adds a 36 px checkbox column with a check-all box in the header (loaded rows only); Space toggles the selected row's box. Checks are independent of the selection. |
| AutoCheckHierarchy | bool | true | Checking a parent checks its enabled descendants; a parent with some descendants checked shows mixed and becomes checked when all are. False keeps every box independent. |
| CanCheckRow | Func<TValue, bool>? | null | False disables the row's box and, through it, every descendant's. |
| CheckedItems | IReadOnlyList<TValue>? | null | The checked rows set by the host, matched by key and re-read whenever the set of keys changes; pair with CheckedItemsChanged for @bind-CheckedItems. |

### Editing

| Name | Type | Default | Description |
|---|---|---|---|
| EditSettingsRef | EditSettings? | null | Turns on the built-in editing: AllowAdding, AllowEditing, AllowDeleting, Mode Inline, Dialog or Batch, entry by double-click, Enter or a click on the active cell. The key and parent key columns are never editable. With it set, cell clicks take the editing path and RowClicked is not raised. Null leaves only the per-column CellEditTemplate. |
| NewItemFactory | Func<TValue>? | null | Creates the record for the toolbar's Add root and Add child; without it Activator.CreateInstance. The record must carry a key no row has. |
| CloneFactory | Func<TValue, TValue>? | null | Returns an independent copy of a record for its edit draft; without it the record is round-tripped through System.Text.Json. Records must be reference types. |
| Validator | Func<TValue, IEnumerable<ValidationResult>>? | null | Extra validation of a draft, run with the data annotations before a commit; its results join the row's messages. |
| ShowEditToolbar | bool | true | The Add root / Add child / Edit row / Delete / Save changes / Cancel changes and Indent / Outdent / Move row buttons above the grid; rendered only with EditSettingsRef or AllowRowDragAndDrop. |
| EditValidatorTemplate | RenderFragment<EditContext>? | null | Rendered with the draft's EditContext above the validation summary of the editing row or dialog. |
| AllowRowDragAndDrop | bool | false | Rows can be dragged onto Before / Inside / After drop zones of another row, Ctrl+Left and Ctrl+Right outdent and indent the selected row, and the toolbar and header menu gain move commands. Blocked while edits are pending. |
| CanDrop | Func<TreeGridRowMoveEventArgs<TValue>, bool>? | null | Vetoes a move before RowMoving; false rejects it with an error message. |

### Query

| Name | Type | Default | Description |
|---|---|---|---|
| AllowSorting | bool | false | Header clicks sort the siblings under each parent, so the hierarchy stays; Shift+click adds a level, and the header menu gains Custom sort and Clear sorting. Columns opt out with their own AllowSorting. |
| AllowMultiSorting | bool | true | False limits Shift+click, the sort dialog and SetSortsAsync to one level. |
| AllowFiltering | bool | false | Adds the header filter button and its popup (two conditions joined by And / Or). Matching rows show with their ancestors and descendants per FilterHierarchyMode; while a filter is active the open state shown is the filter's, not the user's. |
| FilterHierarchyMode | TreeGridFilterHierarchyMode | TreeGridFilterHierarchyMode.Both | None shows matching rows only, Parent adds their ancestors, Child their descendants, Both both. |
| FilterMatchCase | bool | false | Case-sensitive text matching. |
| ShowHeaderFilterIcon | bool | true | False hides the header filter buttons; SetFilterAsync still works. |
| AllowPaging | bool | false | Pages the visible rows (after expansion and filtering) by PageSize, with a Previous / Next pager under the grid; selecting a row moves to its page. |
| PageSize | int | 50 | Rows per page; must be positive or OnParametersSet throws. |

### Columns

| Name | Type | Default | Description |
|---|---|---|---|
| WidthMode | GridWidthMode | GridWidthMode.FillAvailable | FillAvailable stretches the table to the host and shares the width out; FitColumns sizes the table to the sum of the column widths, leaving slack or a horizontal scrollbar, and a resize moves only that column. |
| AllowResizing | bool | false | Drag grips on the headers; a drag that changes the width raises ColumnResized, a double-click on the grip best-fits the column. |
| AllowColumnAutoFit | bool | true | Best fit by grip double-click, the header menu (Best Fit, Best Fit All Columns, Best Fit to Grid) and the AutoFit methods, with GridControl's ColumnAutoFit engine. False removes all of them. |
| AutoFitSampleSize | int | ColumnAutoFit.DefaultSampleSize | Rows measured for a best fit; the constant is 50. |
| AutoFitMinWidth | double | ColumnAutoFit.DefaultMinWidth | Floor in px for a best-fit width; the constant is 40. |
| AutoFitMaxWidth | double | 0 | Ceiling in px for a best-fit width; 0 uses the scroll surface's width. |
| AutoFitUseDomMeasurement | bool | true | Measures the rendered cells through grid-control.js; false estimates from the cell text. |
| FrozenColumns | int | 0 | The first n visible columns stick to the left edge. Columns can also freeze themselves (IsFrozen) or be frozen from the header menu and FreezeColumnAsync. |
| ShowColumnHeaders | bool | true | False drops the header row and with it header sorting, filtering, resizing and the header menu. |
| ShowHeaderContextMenu | bool | true | Right-click on a header opens the menu: freeze, best fit, move, Expand all / Collapse all, sorting and Clear filters. False lets the browser menu through. |
| ShowColumnOptionsButton | bool | false | Enables the Columns panel (show or hide, with a search box), opened by a toolbar item with the Columns action or, with ShowGridOptionsRail, by a rail button. The last visible column cannot be hidden. |
| ShowGridOptionsRail | bool | false | The rail button that opens the Columns panel; needs ShowColumnOptionsButton. |
| Toolbar | List<string>? | null | Toolbar items by text. ExpandAll, CollapseAll, ToggleExpandCollapse, Columns and ClearFilters (and a few aliases) run built-in actions; Refresh only gets its icon and title, and any other text is a custom key. |
| ToolbarItems | IReadOnlyList<GridToolbarItem>? | null | Toolbar items with icon, title, action, disabled state, separators and a drop-down Items list; listed before the Toolbar texts. |
| ShowGridToolbar | bool? | null | Null shows the toolbar when it has items; true or false forces it. |

### Display

| Name | Type | Default | Description |
|---|---|---|---|
| Height | string? | null | CSS height of the root; the rows scroll inside it. Both examples use 440px. |
| Width | string? | null | CSS width of the root. |
| CssClass | string? | null | Classes added to the root. The control reads four of them: fx-treegrid-compact (14 px rows), fx-treegrid-yellow-folder and fx-treegrid-blue-leaf-folder (folder images beside the glyph), fx-treegrid-dotted-lines (connector segments per level, styled by the library stylesheet). |
| EnableHover | bool | true | Adds fx-treegrid-hover to every row for the hover tint. |
| RowCssClassSelector | Func<TValue, int, string?>? | null | Extra class for a row, from its record and display index; an exception from it is swallowed. |
| RowDetailsTemplate | RenderFragment<TValue>? | null | Content under an open row, spanning every column. A row with details counts as a parent and gets the expand icon even without children; mouse and keyboard events inside the details do not reach the row. |
| RowDetailsPredicate | Func<TValue, bool>? | null | Limits the details to the rows it accepts; null gives them to every row. |
| AriaLabel | string | "Tree grid" | aria-label of the table, which has role treegrid. |
| ShowLegacyScrollBar | bool | false | Replaces the native vertical scrollbar with a DOM-drawn Win9x-style one that can be styled and right-clicked. |
| EnableLegacyScrollBarMenu | bool | true | The Scroll Here / Top / Bottom / Page Up / Page Down / Scroll Up / Scroll Down menu on the legacy bar's right-click. |
| LegacyScrollLineHeight | double | 17 | Pixels per line for the legacy bar's arrow buttons and its Scroll Up / Scroll Down commands. |

### Column

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string | "" | Property name on TValue, read by reflection; also the column's key for widths, filters and state. A column without a field is display-only: it cannot sort, filter or be hidden from the panel. |
| HeaderText | string | "" | Header caption; empty shows the field name. |
| Width | string? | null | CSS width; a px value is also the starting width for resizing and best fit. |
| MinWidth | string? | null | CSS min-width; a px value floors a resize (otherwise 32 px) and a best fit. |
| MaxWidth | string? | null | Upper bound for best fit; unset uses AutoFitMaxWidth or the pane width. |
| AllowAutoFit | bool | true | False keeps the column out of Best Fit and Best Fit All Columns; Best Fit to Grid still scales it. |
| Type | ColumnType | ColumnType.Text | Text, Password, Number, Date, Boolean or CheckBox. Picks the default filter operator (Contains for Text, Equals otherwise), the typed filter matching, the numeric best fit and the Date alignment default. |
| TextAlign | TextAlign? | null | Cell and header alignment; unset is Right for Date columns and Left otherwise. |
| Format | string? | null | Format string for IFormattable values, in the current culture; the examples use $#,##0.00, C0 and yyyy-MM-dd. |
| Visible | bool | true | False hides the column; the Columns panel can override it per field. |
| IsFrozen | bool | false | Sticks the column to the FrozenPosition edge; the header menu or FreezeColumnAsync override it. |
| FrozenPosition | FrozenColumnPosition | FrozenColumnPosition.Left | Edge for IsFrozen. |
| IsPrimaryKey | bool | false | Keeps the column out of the built-in editors. |
| AllowEditing | bool | true | False keeps the column out of the built-in editors; key columns and read-only properties are out anyway. |
| AllowSorting | bool | true | False keeps the column out of header-click sorting, the sort dialog and SetSortsAsync. |
| AllowFiltering | bool | true | False removes the column's filter button and makes SetFilterAsync throw for it. |
| AllowResizing | bool | true | False removes the column's resize grip. |
| Template | RenderFragment<object>? | null | Cell content; context is the row as object, cast it to TValue as the org chart does. In the tree column it follows the indent and icons; with a CellEditTemplate it becomes the display inside the click target. |
| HeaderTemplate | RenderFragment? | null | Replaces the header caption. |
| HeaderIconKind | TreeGridHeaderIconKind | TreeGridHeaderIconKind.None | ExpandAll or CollapseAll draws the matching library icon as a header button. The button only raises HeaderIconClicked; the host performs the action. |
| HeaderIconSrc | string? | null | Image URL of the header icon button, overriding the kind's icon. |
| HeaderIconAlt | string? | null | alt text of the header icon, and the button's aria-label when set. |
| HeaderIconTitle | string? | null | Tooltip of the header icon button, and its aria-label when there is no alt. |
| HeaderIconCssClass | string? | null | Extra class on the header icon button. |
| HeaderIconVisible | bool | true | False hides the header icon button. |
| HeaderToolbarItems | IReadOnlyList<GridToolbarItem>? | null | A toolbar inside the header cell with the grid toolbar's item model; built-in actions run after HeaderToolbarItemClicked unless it cancels. |
| EditTemplate | RenderFragment<object>? | null | Replaces the built-in FormItemControl editor of this column during an EditSettingsRef edit; context is the draft. Enter, Escape and Tab are handled by the control around it. |
| CellEditTemplate | RenderFragment<TreeGridCellEditContext>? | null | In-cell editor independent of EditSettingsRef: the cell shows its display inside a click target, a click on the current cell swaps the editor in, and F2, Enter, F4 or typing start it from the keyboard. The context also cascades as ICellEditorHost. |
| CellEditPredicate | Func<object, bool>? | null | Rows that offer the CellEditTemplate; the others render plain. |
| CellEditDisplayCssClass | string? | null | Extra class on the click target, whose base class is fx-treegrid-cell-edit-display. |

### Column events

| Name | Type | Description |
|---|---|---|
| HeaderIconClicked |  | The header icon button was clicked; the control takes no action of its own. |
| HeaderToolbarItemClicked | GridToolbarClickEventArgs | A header toolbar item was clicked, before its built-in action; Cancel skips the action. IsHeaderToolbar is true and ColumnField / ColumnHeader name the column. |

### Events

| Name | Type | Description |
|---|---|---|
| RowSelected | TreeRowSelectEventArgs<TValue> | After a row becomes selected: click, expand-icon click, arrow keys, Home / End, a subscribed right-click, SelectRecordAsync, or a property grid taking focus. Raised again by a click on the already selected row; never with AllowSelection off. |
| RowDeselected | TreeRowSelectEventArgs<TValue> | Before RowSelected whenever one selection replaces another, and from ClearSelectionAsync and SelectRecordAsync(null). The payload carries Data; only ClearSelectionAsync sets RowIndex. GridControl declares this event and never raises it; the tree does. |
| RowClicked | TreeRowClickEventArgs<TValue> | A pointer click on a row, after selection and focus, with the MouseEventArgs; raised even with AllowSelection off. Not raised when EditSettingsRef is set, because cell clicks then stop at the editing path. |
| RowDoubleClicked | TreeRowSelectEventArgs<TValue> | Double-click on a row. With EditSettingsRef.AllowEditing and AllowEditOnDblClick the double-click starts an edit instead. Also Enter's fallback when RowActivated has no handler. |
| RowRightClicked | TreeRowSelectEventArgs<TValue> | Right-click: the row is selected first, then the event fires; the browser contextmenu event still bubbles. Without a handler a right-click changes nothing. |
| RowActivated | TreeRowSelectEventArgs<TValue> | Enter on the selected row, which keeps its state; with no selection Enter selects the first row instead. Not raised when Enter is an edit key: EditSettingsRef with EditOnEnterKey (its default), or a CellEditTemplate on the current cell. |
| OnHostKeyDown | KeyboardEventArgs | Every keydown on the root while no editor is open, before the built-in navigation. Keys the control consumes first (F2, Enter into an editor, Space on a checkbox row, Ctrl+Left / Ctrl+Right with drag-and-drop) do not reach it. |
| Expanded | TreeNodeEventArgs<TValue> | After a parent opens by icon, row click, Space, Right, SetExpandedAsync or a finished child load. Not raised by ExpandAllAsync, ExpandAtLevelAsync, RestoreStateAsync or the toolbar's expand actions, which set the state directly. |
| Collapsed | TreeNodeEventArgs<TValue> | After a parent closes by icon, row click, Space, Left or SetExpandedAsync; the same exclusions as Expanded. |
| CheckedItemsChanged | IReadOnlyList<TValue> | The checked rows (mixed parents excluded) after a box or Space, CheckAllAsync, SetRowCheckedAsync, a commit, a child load or RestoreStateAsync. |
| LoadFailed | string | The exception message when LoadChildren throws; the node closes again and an alert under the grid shows the same text. |
| EditStarting | TreeGridEditEventArgs<TValue> | Before a row enters editing or a new row is added: Original (null for a new row), the Draft and its EditContext; Cancel refuses. |
| DataChanging | TreeGridDataChangeEventArgs<TValue> | Before a save or a move replaces the records, with the list of Add / Update / Delete / Move changes. Cancel, or an Error text, aborts and shows the error. |
| DataChanged | TreeGridDataChangeEventArgs<TValue> | After the records are replaced, with the same args. |
| DataSourceChanged | IEnumerable<TValue> | The new full record list after a commit, for @bind-DataSource; a list handed back this way is recognized as the control's own publication and does not reset its editing state. |
| RowMoving | TreeGridRowMoveEventArgs<TValue> | Before a move is committed (drag, Indent / Outdent, the Move row dialog, MoveRowAsync), after CanDrop; Cancel or Error aborts. |
| RowMoved | TreeGridRowMoveEventArgs<TValue> | After the move, with the moved record and its target. |
| SortChanged | IReadOnlyList<GridSortDescriptor> | After SetSortsAsync, which header clicks, the sort dialog and Clear sorting go through; the full ordered list. |
| PageChanged | int | After GoToPageAsync (the pager, RestoreStateAsync), with the 1-based page. A selection or an edit that lands on another page changes the page without raising it. |
| ColumnResized | ResizeEventArgs | After a grip drag that changed a width, and once per column a best fit changed: Field, OldWidth and NewWidth in px. |
| ToolbarItemClicked | GridToolbarClickEventArgs | A grid toolbar click, before its built-in action; Cancel skips the action. Header toolbar clicks go to the column's HeaderToolbarItemClicked instead. |
| OnToolbarItemClick | string | After the action, with the item's Key; grid toolbar only. |
| LegacyScrollBarRightClicked | MouseEventArgs | Right-click on the legacy scrollbar, before its own menu. |

### Row args

| Name | Type | Default | Description |
|---|---|---|---|
| Data | TValue? | null | The row. |
| RowIndex | int | 0 | Index in the current display order, all pages counted. |
| Level | int | 0 | Depth, 0 for a root. |
| HasChildren | bool | false | The row is a parent: children present, TreatAsParent, or a details template. |
| IsExpanded | bool | false | The row's open state at the time of the event. |
| MouseEvent | MouseEventArgs | new() | TreeRowClickEventArgs only: the click's MouseEventArgs. |

### Node args

| Name | Type | Default | Description |
|---|---|---|---|
| Data | TValue? | null | The parent that opened or closed. |
| Level | int | 0 | Its depth, 0 for a root; the first example prints both. |

### Edit args

| Name | Type | Default | Description |
|---|---|---|---|
| Original | T? |  | The record being edited; null for a new row. |
| Draft | T |  | The copy the editors bind to. |
| EditContext | EditContext |  | The draft's form context, with data annotations enabled. |
| IsNew | bool |  | True for Add root, Add child and AddRecordAsync. |
| Cancel | bool | false | Set in EditStarting to refuse the edit. |

### Change args

| Name | Type | Default | Description |
|---|---|---|---|
| Changes | IReadOnlyList<TreeGridRowChange<T>> |  | One TreeGridRowChange per row: Kind Add, Update, Delete or Move, Original and Data. |
| Cancel | bool | false | Set in DataChanging to abort; ignored by DataChanged. |
| Error | string? | null | Message shown under the grid when the change is refused; setting it aborts on its own. |

### Move args

| Name | Type | Default | Description |
|---|---|---|---|
| Item | T |  | The row being moved. |
| Target | T |  | The row it is dropped on. |
| Position | TreeDropPosition |  | Before, Inside or After the target. |
| Cancel | bool | false | Set in RowMoving to refuse; ignored by RowMoved. |
| Error | string? | null | Message shown when the move is refused; setting it aborts on its own. |

### Resize args

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string | "" | The column key: its field, or its header for a field-less column. |
| OldWidth | double | 0 | Width in px before the change. |
| NewWidth | double | 0 | Width in px after it. |
| Cancel | bool | false | Declared, but TreeGridControl never reads it. |

### Toolbar args

| Name | Type | Default | Description |
|---|---|---|---|
| Key | string | "" | The item's key: its text, or the action name, when none was given. |
| Action | GridToolbarAction | GridToolbarAction.Custom | The resolved built-in action, or Custom. |
| Item | GridToolbarItem? | null | The item as resolved for rendering. |
| IsHeaderToolbar | bool | false | True for a column header toolbar. |
| ColumnField | string? | null | The header toolbar's column field; null for the grid toolbar. |
| ColumnHeader | string? | null | The header toolbar's column caption. |
| Cancel | bool | false | Set to skip the built-in action; OnToolbarItemClick is then not raised either. |

### Methods

| Name | Type | Description |
|---|---|---|
| GetVisibleRecords() | IReadOnlyList<TValue> | Rows in display order: expansion, sorting and filtering applied, all pages. |
| SetExpandedAsync(TValue? item, bool expanded) | Task | Opens or closes one parent, loading its children first when needed; raises Expanded or Collapsed. |
| ExpandAllAsync() | Task | Opens every parent in one pass without raising Expanded; lazy parents load after the render. A pending built-in edit must validate first. Wired to the Expand all button. |
| CollapseAllAsync() | Task | Closes every parent without raising Collapsed; wired to the Collapse all button. |
| ExpandAtLevelAsync(int level) | Task | Opens the parents at 0-based levels up to and including level, without events. |
| CollapseAtLevelAsync(int level) | Task | Closes the parents at that level and deeper, without events. |
| GetSelectedRecord() | TValue? | The selected row, or default. |
| SelectRecordAsync(TValue? item) | Task | Selects a row from code (null clears), raising RowDeselected and, when the item is in the tree, RowSelected. Does not scroll to it or open its ancestors. |
| ClearSelectionAsync() | Task | Clears the selection; RowDeselected carries the row and its index. |
| FocusAsync(bool preventScroll = true) | Task | Focuses the root element. |
| ClearActiveCellEdit() | void | Ends an open CellEditTemplate edit; a no-op in the cursor phase. |
| RenameNodeAsync(object id, string field, string text) | Task<bool> | Writes a string property of a loaded record in place, without a rebuild, events or validation. False when the row is gone, being edited or deleted; throws for a key column or a non-string field. |

### Edit methods

| Name | Type | Description |
|---|---|---|
| GetCheckedRecords() | IReadOnlyList<TValue> | The checked rows; mixed parents are not included. |
| SetRowCheckedAsync(object id, bool value) | Task | Checks or unchecks a row by key, cascading per AutoCheckHierarchy; raises CheckedItemsChanged. |
| CheckAllAsync(bool value = true) | Task | Checks or unchecks every loaded row, collapsed, filtered and paged ones included; disabled branches are skipped. |
| GetCurrentRecords() | IReadOnlyList<TValue> | The loaded records, lazily loaded children included, as last committed; pending drafts and deletions are not applied. |
| BeginEditAsync(object id, string? field = null) | Task<bool> | Starts the built-in edit of a visible row, in the first editable column when field is null. False when editing is off, the row is hidden or EditStarting cancels. |
| AddRecordAsync(TValue item, object? parentId = null) | Task<bool> | Adds a draft under parentId (null: a root) and opens its editor; the item's key must be new. |
| SaveChangesAsync() | Task<bool> | Validates every draft, raises DataChanging, replaces the records and raises DataSourceChanged and DataChanged. False on a validation error or a cancel. |
| CancelChangesAsync() | Task | Discards every draft and pending deletion. |
| CancelEditAsync() | Task | Discards the draft of the row being edited only. |
| DeleteRecordsAsync(IEnumerable<object> ids) | Task<bool> | Deletes the rows and their descendants: at once, or as pending changes in Batch mode. |
| MoveRowAsync(object sourceId, object targetId, TreeDropPosition position = TreeDropPosition.Inside) | Task<bool> | Moves a row and its branch before, inside or after another. Needs AllowRowDragAndDrop, no pending edits and, for reordering siblings, no sort; raises RowMoving, the data events and RowMoved. |
| IndentAsync(object id) | Task<bool> | Moves the row inside its previous sibling. |
| OutdentAsync(object id) | Task<bool> | Moves the row after its parent. |

### Query methods

| Name | Type | Inputs | Description |
|---|---|---|---|
| AddColumn(TreeGridColumn column) / RemoveColumn(TreeGridColumn column) | void |  | Column registration; TreeGridColumn calls them itself when it initializes and disposes. |
| FreezeColumnAsync(string field, FrozenColumnPosition? position) | Task |  | Freezes a column left or right, or unfreezes it with null; throws for an unknown field. |
| AutoFitColumnsAsync() | Task |  | Best-fits every visible column to its content. |
| AutoFitColumnAsync(string field) | Task |  | Best-fits one column, by field or by header for a field-less column. |
| FitColumnsToGridAsync() | Task |  | Scales the visible columns proportionally so together they fill the width exactly. |
| GetSorts() | IReadOnlyList<GridSortDescriptor> |  | The sort levels in priority order. |
| SetSortsAsync(IEnumerable<GridSortDescriptor> sorts) | Task |  | Replaces the sort levels (empty clears) and raises SortChanged. Throws for a repeated or non-sortable field, or several levels with AllowMultiSorting off. |
| OpenSortDialogAsync() | Task |  | Opens the Custom sort dialog; needs AllowSorting. |
| GetFilters() | IReadOnlyList<TreeGridFilter> |  | The active filters, one per column. |
| SetFilterAsync(TreeGridFilter filter) | Task |  | Sets one column's filter (field, operator, value, optional second condition and And / Or) and returns to page 1; throws for a non-filterable field. |
| ClearFiltersAsync() | Task |  | Clears every column filter. |
| GoToPageAsync(int page) | Task |  | Moves to a page, clamped to the range, and raises PageChanged. |
| CaptureState() | TreeGridViewState |  | Sorts, filters, expanded and selected keys, filter mode and case, page and page size, column visibility and widths, frozen columns and checked keys, with keys as invariant strings. |
| RestoreStateAsync(TreeGridViewState state) | Task |  | Applies a captured state: sorts are validated first, then filters, expansion, selection, columns, checks and the page, which raises PageChanged. |
| Export() | GridExportResult | GridExportFormat formatstring fileName = "Tree"bool allLoaded = false | The visible rows of every page or, with allLoaded, every loaded row, in the chosen GridExportFormat, with a Level column first and parents in bold. Children not yet loaded are not fetched. |
| DownloadAsync() | Task | GridExportFormat formatstring fileName = "Tree"bool allLoaded = false | Export, then hands the file to the browser. |

### Props

| Name | Type | Description |
|---|---|---|
| HasExpandableNodes | bool | Any parent in the tree. |
| AreAllExpandableNodesExpanded | bool | Every parent is open; drives the toolbar's ToggleExpandCollapse icon. |
| HasPendingChanges | bool | Drafts or pending deletions exist. |
| CurrentEditContext | EditContext? | The EditContext of the row being edited, or null. |
| CurrentPage | int | The 1-based page, clamped to PageCount. |
| PageCount | int | Pages of visible rows at the current PageSize; at least 1. |

## Examples

### Org

```razor
@using Fx.ControlKit
@using Fx.ControlKit.Grid

<TextBoxControl Value="@_search" ValueChanged="Search" Placeholder="Name, title, office or division" Width="240px" />

<TreeGridControl @key="_orgGeneration"
                 TValue="StaffMember"
                 DataSource="@_shown"
                 IdMapping="Id"
                 ParentIdMapping="ManagerId"
                 TreeColumnIndex="0"
                 EnableCollapseAll="true"
                 InitialExpansionPredicate="@(p => !string.IsNullOrEmpty(_search) || p.Level < 1)"
                 AllowSorting="true"
                 AllowSelection="true"
                 ToggleOnRowClick="false"
                 Height="440px">
    <TreeGridColumn Field="@nameof(StaffMember.Name)" HeaderText="Name" Width="290px" IsFrozen="true">
        <Template>
            @{ var p = (StaffMember)context; }
            @if (p.Vacant) { <em class="vacant">Vacant</em> } else { <strong>@p.Name</strong> }
            @if (p.OnLeave) { <span class="tag">on leave</span> }
        </Template>
    </TreeGridColumn>
    <TreeGridColumn Field="@nameof(StaffMember.Title)" HeaderText="Title" Width="230px" />
    <TreeGridColumn Field="@nameof(StaffMember.Office)" HeaderText="Office" Width="110px" />
    <TreeGridColumn Field="@nameof(StaffMember.Headcount)" HeaderText="People below" Width="110px" TextAlign="TextAlign.Right">
        <Template>@(((StaffMember)context).Headcount is > 0 and var n ? n.ToString("N0") : "")</Template>
    </TreeGridColumn>
    <TreeGridColumn Field="@nameof(StaffMember.Grade)" HeaderText="Grade" Width="70px" TextAlign="TextAlign.Center" />
    <TreeGridColumn Field="@nameof(StaffMember.Contract)" HeaderText="Contract" Width="160px">
        <Template>
            @{ var p = (StaffMember)context; }
            @p.Contract@(p.Fte < 1 ? $", {p.Fte:0.0} FTE" : "")
        </Template>
    </TreeGridColumn>
    <TreeGridColumn Field="@nameof(StaffMember.Salary)" HeaderText="Salary" Width="100px" TextAlign="TextAlign.Right" Format="C0" />
    <TreeGridColumn Field="@nameof(StaffMember.Rating)" HeaderText="Rating" Width="120px">
        <Template>
            @{ var p = (StaffMember)context; }
            @if (p.Rating is { } stars) { <RatingControl Value="@stars" ReadOnly="true" /> }
            else if (!p.Vacant) { <span class="muted">new starter</span> }
        </Template>
    </TreeGridColumn>
    <TreeGridColumn Field="@nameof(StaffMember.Started)" HeaderText="Started" Width="100px" TextAlign="TextAlign.Center" Format="yyyy-MM-dd" />
    <TreeGridColumn Field="@nameof(StaffMember.DottedLineId)" HeaderText="Also reports to" Width="190px">
        <Template>@DottedLine((StaffMember)context)</Template>
    </TreeGridColumn>
</TreeGridControl>
<p class="result">@OrgStatus</p>
```

```csharp
// Org chart: Razor Sharp Getaways' staff (Data/TravelOrg.cs). A search keeps every match's managers, so the tree stays
// rooted.
private static readonly IReadOnlyList<StaffMember> _staff = TravelOrg.Staff;
private static readonly Dictionary<string, StaffMember> _byId = _staff.ToDictionary(p => p.Id);
private string? _search;
private List<StaffMember> _shown = _staff.ToList();
private int _orgGeneration = 1;   // @key: a new value remounts the tree grid when the list is swapped

private string OrgStatus =>
    $"{_shown.Count:N0} of {_staff.Count:N0} posts shown; {_shown.Count(p => p.Vacant)} vacant, {_shown.Count(p => p.OnLeave)} on leave.";

private static string DottedLine(StaffMember p) =>
    p.DottedLineId is { } id ? _byId[id] is { Vacant: true } v ? $"{v.Title} (vacant)" : _byId[id].Name : "";

private void Search(string? text)
{
    _search = text?.Trim();
    var keep = _staff
        .Where(p => string.IsNullOrEmpty(_search)
                    || new[] { p.Name, p.Title, p.Office, p.Division, p.Department }.Any(v => v.Contains(_search, StringComparison.OrdinalIgnoreCase)))
        .Select(p => p.Id)
        .ToHashSet();
    foreach (var id in keep.ToList())
        for (var manager = _byId[id].ManagerId; manager is not null && keep.Add(manager); manager = _byId[manager].ManagerId) { }
    _shown = _staff.Where(p => keep.Contains(p.Id)).ToList();
    _orgGeneration++;
}

// Data/TravelOrg.cs: one post; TravelOrg.Staff generates the list from a fixed seed.
public sealed record StaffMember
{
    public required string Id { get; init; }
    public string? ManagerId { get; init; }
    public string? DottedLineId { get; init; }
    public required string Name { get; init; }        // "Vacant" for an open post
    public required string Title { get; init; }
    public int Grade { get; init; }                   // 1 trainee to 9 chief executive
    public required string Division { get; init; }
    public required string Department { get; init; }
    public required string Office { get; init; }
    public required string Country { get; init; }
    public required string Region { get; init; }
    public required string Contract { get; init; }    // Permanent, Fixed-term, Seasonal or Contractor
    public double Fte { get; init; } = 1;             // 1 full time; 0.5 to 0.8 part time
    public DateOnly? Started { get; init; }
    public decimal Salary { get; init; }              // USD a year at the post's FTE; the budget for a vacant post
    public int? Rating { get; init; }                 // 1 to 5; none for vacant posts and people who started under six months ago
    public string Languages { get; init; } = "";
    public string Email { get; init; } = "";
    public bool Vacant { get; init; }
    public bool OnLeave { get; init; }
    public int Level { get; init; }                   // 0 for the chief executive
    public int DirectReports { get; init; }           // posts reporting on the solid line, vacant ones included
    public int Headcount { get; init; }               // people below on the solid line, vacant posts not counted
}
```

### Airports

```razor
@using Fx.ControlKit.Grid

<TreeGridControl @ref="_places"
                 TValue="Place"
                 DataSource="@_continents"
                 IdMapping="Id"
                 ParentIdMapping="ParentId"
                 TreeColumnIndex="0"
                 TreatAsParent="@(p => p.Level < 2 || (p.Level == 2 && p.Runways > 0))"
                 LoadChildren="LoadPlacesAsync"
                 EnableCollapseAll="true"
                 InitialExpansionPredicate="@(p => p.Name == "Europe")"
                 AllowSorting="true"
                 AllowSelection="true"
                 Height="440px"
                 Expanded="@(a => _last = $"opened {a.Data?.Name}")"
                 Collapsed="@(a => _last = $"closed {a.Data?.Name}")">
    <TreeGridColumn Field="@nameof(Place.Name)" HeaderText="Place" Width="340px" />
    <TreeGridColumn Field="@nameof(Place.Detail)" HeaderText="Type or surface" Width="150px" />
    <TreeGridColumn Field="@nameof(Place.Airports)" HeaderText="Airports" Width="80px" TextAlign="TextAlign.Right" Format="N0" />
    <TreeGridColumn Field="@nameof(Place.Runways)" HeaderText="Runways" Width="80px" TextAlign="TextAlign.Right" Format="N0" />
    <TreeGridColumn Field="@nameof(Place.LongestRunwayFt)" HeaderText="Longest runway (ft)" Width="140px" TextAlign="TextAlign.Right" Format="N0" />
    <TreeGridColumn Field="@nameof(Place.ElevationFt)" HeaderText="Elevation (ft)" Width="110px" TextAlign="TextAlign.Right" Format="N0" />
</TreeGridControl>
<p class="result">@_loaded.ToString("N0") of @_total.ToString("N0") rows loaded@(_last is null ? "" : $" · last {_last}")</p>
```

```csharp
// Airports: the six continents are the whole DataSource; LoadChildren supplies the rest a level at a time.
// A row's Id is its path, "Europe|PT|LIS|03/21", so the loader can tell from it what to return.
private TreeGridControl<Place>? _places;
private readonly List<Place> _continents = AirportData.Airports
    .GroupBy(a => a.Continent)
    .OrderBy(g => g.Key)
    .Select(g => Group(g.Key, null, g.Key, g))
    .ToList();
private int _loaded = 6;
private readonly int _total = 6 + AirportData.Airports.Select(a => (a.Continent, a.CountryCode)).Distinct().Count()
    + AirportData.Airports.Count + AirportData.Airports.Sum(a => a.Runways);
private string? _last;

private Task<IReadOnlyList<Place>> LoadPlacesAsync(Place parent, CancellationToken token)
{
    var path = parent.Id.Split('|');
    IReadOnlyList<Place> children = path.Length switch
    {
        1 => AirportData.Airports.Where(a => a.Continent == path[0])
                .GroupBy(a => (a.CountryCode, a.Country))
                .OrderBy(g => g.Key.Country)
                .Select(g => Group($"{parent.Id}|{g.Key.CountryCode}", parent.Id, g.Key.Country, g))
                .ToList(),
        2 => AirportData.Airports.Where(a => a.Continent == path[0] && a.CountryCode == path[1])
                .OrderBy(a => a.Type).ThenBy(a => a.Code)
                .Select(a => new Place($"{parent.Id}|{a.Code}", parent.Id, $"{a.Code} · {a.Name}", $"{a.Type} airport",
                    null, a.Runways, a.LongestRunwayFt, a.ElevationFt))
                .ToList(),
        _ => AirportData.RunwaysOf(path[2]).Where(r => !r.Closed)
                .OrderByDescending(r => r.LengthFt)
                .Select(r => new Place($"{parent.Id}|{r.Name}", parent.Id, $"Runway {r.Name}",
                    r.Lighted ? $"{r.Surface}, lighted" : r.Surface, null, null, r.LengthFt, null))
                .ToList()
    };
    _loaded += children.Count;
    return Task.FromResult(children);
}

private static Place Group(string id, string? parentId, string name, IEnumerable<Airport> airports) =>
    new(id, parentId, name, "", airports.Count(), airports.Sum(a => a.Runways), airports.Max(a => a.LongestRunwayFt), null);

private sealed record Place(string Id, string? ParentId, string Name, string Detail,
    int? Airports, int? Runways, int? LongestRunwayFt, int? ElevationFt)
{
    public int Level => Id.Count(c => c == '|');
}
```

