Theme
Version
GitHub PyPI Discord
On this page

Data Grid

Use CDataGrid for application data that benefits from one composite Tab stop, cell navigation, row selection, accepted complete-collection sorting, or fixed-height server windowing. Use CTable instead for document-like tables, ordinary links and controls in cells, spans, footers, and print-first reading.

Build a complete grid

Columns and rows are immutable Python records. Every Row supplies exactly one Cell value for every Column key, and every key is a stable nonempty string.

Navigate a complete Data Grid
Show code
import citry_ui
from citry import Component, citry
from citry_ui import CDataGridColumn, CDataGridRow

citry.register_library(citry_ui)


class DataGridAtAGlance(Component):
    template = """
      <c-CDataGrid c-columns="columns" c-rows="rows" label="Project members" striped>
        <c-fill name="caption">Current project members</c-fill>
      </c-CDataGrid>
    """

    def template_data(self, _kwargs: object, _slots: object) -> dict[str, object]:
        return {
            "columns": (
                CDataGridColumn("name", "Name", width=190),
                CDataGridColumn("role", "Role", width=180),
                CDataGridColumn("status", "Status", width=130),
            ),
            "rows": (
                CDataGridRow("ada", {"name": "Ada Lovelace", "role": "Engineer", "status": "Active"}),
                CDataGridRow("grace", {"name": "Grace Hopper", "role": "Admiral", "status": "Active"}),
                CDataGridRow("katherine", {"name": "Katherine Johnson", "role": "Mathematician", "status": "Away"}),
            ),
        }


preview = DataGridAtAGlance()
preview  # noqa: B018

The server output is a native table with exact row and column positions. Once enhanced, one Header or Cell is in the page Tab order. Arrow keys move between rendered Cells; Home, End, Page Up, Page Down, Ctrl/Cmd+Home, and Ctrl/Cmd+End provide larger movement.

Request sorting and select rows

Set sortable=True on Columns that can be sorted. Header activation cycles ascending, descending, then unsorted. onSortChange receives the requested model, and accepted sort state must come back from the owner. When that accepted request belongs to a complete supplied collection, the grid visibly reorders Rows by rendered Cell text. It uses locale-aware numeric comparison, applies sort entries in priority order, and restores server order when sorting is cleared. Shift preserves other Columns when multi_sort=True.

Sort and select people
Show code
import citry_ui
from citry import Component, citry
from citry_ui import CDataGridColumn, CDataGridRow, CDataGridSort

citry.register_library(citry_ui)


class DataGridSortingSelection(Component):
    template = """
      <section x-data="{sort:[{key:'name',direction:'asc'}],notice:'Activate a sortable header or select a row'}">
        <output x-text="notice">Activate a sortable header or select a row</output>
        <c-CDataGrid
          c-columns="columns"
          c-rows="rows"
          c-sort="sort"
          label="Sortable people"
          selection="multiple"
          c-selected="['grace']"
          $c-props="{
            sort,
            onSortChange:(next)=>{
              sort=next;
              notice=next.length
                ? `Sorted: ${next.map((item,index)=>`${index + 1}. ${item.key} ${item.direction}`).join(', ')}`
                : 'Server row order restored';
            },
            onSelectionChange:(selected)=>notice=`Selected: ${selected.join(', ') || 'none'}`,
          }"
        />
      </section>
    """

    def template_data(self, _kwargs: object, _slots: object) -> dict[str, object]:
        return {
            "columns": (
                CDataGridColumn("name", "Name", sortable=True, width=190),
                CDataGridColumn("team", "Team", sortable=True, width=150),
                CDataGridColumn("score", "Score", sortable=True, width=100, align="end"),
            ),
            "rows": (
                CDataGridRow("ada", {"name": "Ada Lovelace", "team": "Platform", "score": 98}),
                CDataGridRow("grace", {"name": "Grace Hopper", "team": "Compiler", "score": 95}),
                CDataGridRow("lin", {"name": "Lin Clark", "team": "Runtime", "score": 91}),
            ),
            "sort": (CDataGridSort("name", "asc"),),
        }


preview = DataGridSortingSelection()
preview  # noqa: B018

selection="single" or selection="multiple" enables Row selection. Uncontrolled selection commits immediately. A non-null client selected array makes selection controlled, so the visible state waits for acceptance. In multiple mode, drag a mouse pointer across loaded Rows to select a range; starting on a selected Row removes the dragged range. Disabled Rows are skipped. Shift+Space toggles the focused Row in either direction. Touch remains ordinary scrolling rather than starting a drag selection.

Control models from Alpine

Pass sort, selected, and callbacks through $c-props. Invalid client models are diagnosed and the last valid state remains active.

Control Data Grid models
Show code
import citry_ui
from citry import Component, citry
from citry_ui import CDataGridColumn, CDataGridRow

citry.register_library(citry_ui)


class ControlledDataGrid(Component):
    template = """
      <section x-data="{sort:[],selected:['ada']}">
        <button type="button" @click="selected=[]">Clear selection</button>
        <c-CDataGrid
          c-columns="columns"
          c-rows="rows"
          label="Controlled members"
          selection="multiple"
          $c-props="{
            sort,
            selected,
            onSortChange:(next)=>sort=next,
            onSelectionChange:(next)=>selected=next,
          }"
        />
      </section>
    """

    def template_data(self, _kwargs: object, _slots: object) -> dict[str, object]:
        return {
            "columns": (
                CDataGridColumn("name", "Name", sortable=True, width=190),
                CDataGridColumn("role", "Role", sortable=True, width=170),
            ),
            "rows": (
                CDataGridRow("ada", {"name": "Ada Lovelace", "role": "Engineer"}),
                CDataGridRow("grace", {"name": "Grace Hopper", "role": "Admiral"}),
            ),
        }


preview = ControlledDataGrid()
preview  # noqa: B018

Sort remains request/accept so an application can reject it or wait for a server response. Initial and programmatic models describe the server-authored order; local reordering occurs when the browser accepts a Header request for a complete collection. A server window cannot sort Rows it does not have, so its owner must return the newly ordered range. Selection becomes uncontrolled again when client selected is omitted or null. Accepted changes are announced politely.

Supply a server window

Set total_count and start_index when rows is one contiguous window of a larger collection. row_height is fixed geometry. onRangeChange receives a half-open desired range when scrolling, resizing, or navigation leaves the supplied range.

Request Data Grid windows
Show code
import citry_ui
from citry import Component, citry
from citry_ui import CDataGridColumn, CDataGridRow

citry.register_library(citry_ui)


class WindowedDataGrid(Component):
    template = """
      <section x-data="{notice:'This static preview supplies one complete window'}">
        <output x-text="notice">This static preview supplies one complete window</output>
        <c-CDataGrid
          c-columns="columns"
          c-rows="rows"
          label="Audit records"
          c-total_count="16"
          c-row_height="44"
          $c-props="{onRangeChange:(detail)=>notice=`Requested ${detail.startIndex}-${detail.endIndex - 1}`}"
        />
      </section>
    """

    def template_data(self, _kwargs: object, _slots: object) -> dict[str, object]:
        return {
            "columns": (
                CDataGridColumn("number", "Record", width=120),
                CDataGridColumn("action", "Action", width=230),
                CDataGridColumn("actor", "Actor", width=160),
            ),
            "rows": tuple(
                CDataGridRow(
                    f"audit-{index}",
                    {"number": f"#{index + 1:05d}", "action": "Signed deployment record", "actor": "Release bot"},
                )
                for index in range(16)
            ),
        }


preview = WindowedDataGrid()
preview  # noqa: B018

The component does not fetch. The owner handles supersession, retries, offline state, and replacement. Keep Row keys stable across windows. This first version does not select unloaded rows or expose a remote select-all operation.

Edit cells in place

Set editable=True on a CDataGridColumn, then choose its editor from text, number, checkbox, or select. Select editors require named CDataGridEditOption records. editor_attrs accepts only the documented attributes for that native control, such as min, max, step, maxlength, and placeholder.

Edit project assignments
Show code
# ruff: noqa: ANN001, ANN201 - public snippets keep focus on component use

import citry_ui
from citry import Component, citry
from citry_ui import CDataGridColumn, CDataGridEditOption, CDataGridRow

citry.register_library(citry_ui)


class EditableDataGrid(Component):
    def template_data(self, _kwargs, _slots):
        return {
            "columns": (
                CDataGridColumn("name", "Name", editable=True, editor_attrs={"maxlength": 80}),
                CDataGridColumn(
                    "role",
                    "Role",
                    editable=True,
                    editor="select",
                    editor_options=(
                        CDataGridEditOption("engineer", "Engineer"),
                        CDataGridEditOption("designer", "Designer"),
                        CDataGridEditOption("lead", "Lead"),
                    ),
                ),
                CDataGridColumn(
                    "allocation",
                    "Allocation",
                    editable=True,
                    editor="number",
                    editor_attrs={"min": 0, "max": 100, "step": 5},
                ),
                CDataGridColumn("active", "Active", editable=True, editor="checkbox"),
            ),
            "rows": (
                CDataGridRow("ada", {"name": "Ada", "role": "engineer", "allocation": 80, "active": True}),
                CDataGridRow("mira", {"name": "Mira", "role": "designer", "allocation": 60, "active": True}),
            ),
        }

    template = """
      <section x-data="{last:'Double-click or press Enter to edit'}">
        <c-CDataGrid
          c-columns="columns"
          c-rows="rows"
          label="Project assignments"
          $c-props="{onCellEditCommit:(value,detail)=>last=`${detail.rowKey}.${detail.columnKey}: ${value}`}"
        />
        <output x-text="last">Double-click or press Enter to edit</output>
      </section>
    """


preview = EditableDataGrid()
preview  # noqa: B018

Enter, F2, typing, Backspace, Delete, or double-click enters edit mode where appropriate. Enter commits, Escape cancels, and Tab commits before moving to the adjacent Cell. onCellEditCommit receives the typed value and stable Row and Column details. Returning False rejects the value and keeps the editor open. The component does not mutate server Rows: update the owner and render the accepted value back into rows.

The static documentation preview uses a small self-contained range with no omitted leading or trailing Rows. It therefore never exposes scrollable blank space that the static page cannot replace. In an application, a partial range keeps its spacers only until the owner replaces it after onRangeChange.

Loading, empty, and error states

state="loading" and state="error" replace ready Rows with one spanning state output. Ready with total_count=0 becomes empty. Fill the corresponding Slot for richer server content, or override the plain localized label.

Render Data Grid states
Show code
import citry_ui
from citry import Component, citry
from citry_ui import CDataGridColumn, CDataGridRow

citry.register_library(citry_ui)


class DataGridStates(Component):
    template = """
      <div class="grid-states">
        <c-CDataGrid c-columns="columns" c-rows="[]" label="Empty records" />
        <c-CDataGrid c-columns="columns" c-rows="rows" label="Loading records" state="loading" />
        <c-CDataGrid c-columns="columns" c-rows="rows" label="Failed records" state="error">
          <c-fill name="error"><strong>Records are unavailable.</strong> Try again from the toolbar.</c-fill>
        </c-CDataGrid>
      </div>
    """
    css = ":where(.grid-states){display:grid;gap:1rem}"

    def template_data(self, _kwargs: object, _slots: object) -> dict[str, object]:
        return {
            "columns": (CDataGridColumn("name", "Name"), CDataGridColumn("status", "Status")),
            "rows": (CDataGridRow("placeholder", {"name": "Placeholder", "status": "Pending"}),),
        }


preview = DataGridStates()
preview  # noqa: B018

Accessibility and Cell content

The family follows the ARIA data-grid interaction model. Header and Cell Slot content cannot contain caller-authored links, buttons, inputs, editable content, or another Tab stop; focus remains on the Header or Cell. Built-in editors temporarily move focus into one owned native control. Use onCellActivate for Enter and double-click activation on noneditable Cells.

Use exact positions and disabled Rows
Show code
import citry_ui
from citry import Component, citry
from citry_ui import CDataGridColumn, CDataGridRow

citry.register_library(citry_ui)


class AccessibleDataGrid(Component):
    template = """
      <c-CDataGrid
        c-columns="columns"
        c-rows="rows"
        label="Deployment approvals"
        selection="multiple"
      >
        <c-fill name="caption">Use Arrow keys to move and Shift+Space to select an enabled Row.</c-fill>
      </c-CDataGrid>
    """

    def template_data(self, _kwargs: object, _slots: object) -> dict[str, object]:
        return {
            "columns": (
                CDataGridColumn("change", "Change", width=240),
                CDataGridColumn("owner", "Owner", width=160),
                CDataGridColumn("status", "Approval status", width=160),
            ),
            "rows": (
                CDataGridRow("api", {"change": "API release", "owner": "Ada", "status": "Approved"}),
                CDataGridRow(
                    "locked",
                    {"change": "Security policy", "owner": "Grace", "status": "Locked"},
                    disabled=True,
                ),
                CDataGridRow("docs", {"change": "Guide update", "owner": "Lin", "status": "Review"}),
            ),
        }


preview = AccessibleDataGrid()
preview  # noqa: B018

Column labels and Cell values belong to the application and should already be localized. State labels and browser announcements use the Citry UI catalog by default. Explicit label overrides remain caller-owned and do not switch with the client locale.

Styling and scope boundaries

Use density, striped, column_borders, and sticky_header for common presentation. Customize the root and native table separately with attrs and table_attrs, or use the documented public variables and part selectors.

Customize a Data Grid
Show code
import citry_ui
from citry import Component, citry
from citry_ui import CDataGridColumn, CDataGridRow

citry.register_library(citry_ui)


class CustomizedDataGrid(Component):
    template = """
      <div class="custom-grid">
        <c-CDataGrid
          c-columns="columns"
          c-rows="rows"
          label="Compact metrics"
          density="compact"
          striped
          column_borders
          c-style="{
            '--cui-data-grid-radius':'1rem',
            '--cui-data-grid-selected-background':'color-mix(in srgb, #7c3aed 20%, Canvas)',
          }"
        />
      </div>
    """
    css = """
      :where(.custom-grid [data-citry-ui-part="header-cell"]) { text-transform:uppercase;letter-spacing:.04em; }
      :where(.custom-grid [data-column-key="value"]) { font-variant-numeric:tabular-nums; }
    """

    def template_data(self, _kwargs: object, _slots: object) -> dict[str, object]:
        return {
            "columns": (
                CDataGridColumn("metric", "Metric", width=220),
                CDataGridColumn("value", "Value", width=120, align="end"),
            ),
            "rows": (
                CDataGridRow("latency", {"metric": "P95 latency", "value": "128 ms"}),
                CDataGridRow("errors", {"metric": "Error rate", "value": "0.04%"}),
                CDataGridRow("uptime", {"metric": "Uptime", "value": "99.99%"}),
            ),
        }


preview = CustomizedDataGrid()
preview  # noqa: B018

Arbitrary caller-authored Cell widgets, built-in filtering, grouping, aggregation, pivoting, tree Rows, pinning, reordering, resizing, clipboard mutation, export, and browser-owned data sources are outside this first family. Compose application controls around the grid instead.

API reference

Inputs

CDataGrid server inputs

Server inputs are passed in a template through <c-CDataGrid ... /> or in Python through CDataGrid(...).

InputTypeDefaultEffect
columnsSequence[CDataGridColumn]requiredDefines the nonempty ordered structural Column schema.
rowsSequence[CDataGridRow]requiredSupplies a complete collection or one contiguous server window.
labelstrrequiredSupplies the required accessible grid name.
idstr | NonegeneratedSets root identity and bases stable Header Row and Cell IDs.
stateCDataGridState (CDataGridState)"ready"Selects ready loading or error output; zero ready Rows become empty.
sortSequence[CDataGridSort]"()"Supplies the initial server-authored ordered sort model.
multi_sortboolTrueAllows Shift-modified sort requests to preserve other Columns.
selectionCDataGridSelection (CDataGridSelection)"none"Selects no single or multiple supplied-Row selection.
selectedSequence[str]"()"Supplies unique initially selected Row keys.
disabledboolFalseBlocks sorting selection activation editing and navigation.
total_countint | NoneNoneSets logical Row count; omission means the complete supplied collection.
start_indexint0Sets the zero-based logical index of the first supplied Row.
row_heightint48Sets the fixed Row stride in CSS pixels.
viewport_sizeint400Sets initial scroll-viewport block size in CSS pixels.
overscanint3Adds 0 through 100 Rows around each desired range.
initial_indexint0Performs one initial scroll to a clamped logical Row.
densityCDataGridDensity (CDataGridDensity)"comfortable"Selects compact comfortable or spacious Row presentation.
stripedboolFalseAdds alternate supplied-Row surfaces.
column_bordersboolFalseShows boundaries between Columns.
sticky_headerboolTrueKeeps Headers at the viewport block start.
loading_labelstr"Loading data..."Overrides the localized loading state.
empty_labelstr"No data."Overrides the localized empty state.
error_labelstr"Unable to load data."Overrides the localized error state.
sort_ascending_labelstr"{column} sorted ascending"Overrides ascending-sort announcements and must retain column.
sort_descending_labelstr"{column} sorted descending"Overrides descending-sort announcements and must retain column.
sort_cleared_labelstr"Sort cleared for {column}"Overrides cleared-sort announcements and must retain column.
selected_one_labelstr"One row selected"Overrides the one-Row selection announcement.
selected_labelstr"{count} rows selected"Overrides multi-Row selection announcements and must retain count.
edit_labelstr"Edit {column}"Overrides owned editor names and must retain column.
editing_labelstr"Editing {column}"Overrides edit-start announcements and must retain column.
edit_submitted_labelstr"Changes submitted for {column}"Overrides edit-commit announcements and must retain column.
edit_cancelled_labelstr"Changes cancelled for {column}"Overrides edit-cancel announcements and must retain column.
edit_invalid_labelstr"Enter a valid value for {column}"Overrides rejected or invalid edit announcements and must retain column.
class_CClassValue | None (CClassValue)NoneAdds root classes.
styleCStyleValue | None (CStyleValue)NoneAdds root styles merged with owned geometry variables.
attrsMapping[str, object] | NoneNoneAdds copied allowed root attributes without replacing state or runtime ownership.
table_attrsMapping[str, object] | NoneNoneAdds copied allowed native table attributes without replacing Grid semantics or positions.

CDataGrid client inputs

Client inputs are passed in the browser through the $c-props="{ ... }" attribute on <c-CDataGrid />.

InputTypeOmitted behaviorEffect
sortArray<{key: string, direction: "asc" | "desc"}> | nullUses the server sort model.Accepts sort indicators and reorders a complete collection after a matching Header request.
selectedstring[] | nullOmission or null releases control to committed selection.Controls unique supplied-Row selection while supplied.
disabledbooleanUses the server value.Reactively disables owned interaction.
overscannumberUses the server value.Reactively changes desired range buffering.
onSortChangefunctionSort activation emits no callback.Receives request-only sort changes.
onSelectionChangefunctionSelection still commits when uncontrolled.Receives selection requests or commits.
onRangeChangefunctionUncovered ranges only reflect pending state.Receives animation-frame-coalesced desired ranges.
onCellActivatefunctionEnter and double-click have no activation callback.Receives enabled Cell activation.
onCellEditStartfunctionNo edit-start callback runs.Receives entry into an owned native editor.
onCellEditCommitfunctionValid edits close without a data-change request.Receives changed typed values; returning false rejects synchronously.
onCellEditCancelfunctionNo edit-cancel callback runs.Receives Escape and reactive disabling cancellations.

Slots

Slots are passed as nested content or <c-fill> tags in a template, or through the slots={...} argument in Python.

CDataGrid slots

SlotRequiredDataFallback
captionno{} (CDataGridCaptionSlotData)Omitted.
toolbarno{} (CDataGridToolbarSlotData)Omitted before the viewport.
headerno{column, column_index, sort_direction, sort_priority} (CDataGridHeaderSlotData)Escaped Column label plus owned sort indicator.
cellno{row, column, cell, row_index, column_index, selected} (CDataGridCellSlotData)Escaped or component-like Cell value.
loadingno{} (CDataGridLoadingSlotData)Localized loading label.
emptyno{} (CDataGridEmptySlotData)Localized empty label.
errorno{} (CDataGridErrorSlotData)Localized error label.

Events

Component events are callback inputs supplied through $c-props. Native browser events remain available through Alpine @... attributes.

CDataGrid events

EventSignatureTrigger and timingDetailControlled and cancellation behavior
onSortChange(sort: sort[], detail: CDataGridSortChangeDetail) => void (CDataGridSortChangeDetail)Click or Enter activates an enabled sortable Header.{sort, previousSort, columnKey, direction, source, sourceEvent} (CDataGridSortChangeDetail)Request-only until accepted; a matching accepted request reorders complete supplied Rows by rendered text while a partial window waits for server replacement.
onSelectionChange(selected: string[], detail: CDataGridSelectionChangeDetail) => void (CDataGridSelectionChangeDetail)Click Shift+click Shift+Space or mouse drag requests a supplied-Row selection change.{selected, previousSelected, changed, rowKey, selectedRow, controlled, source, sourceEvent} (CDataGridSelectionChangeDetail)Uncontrolled state commits first; controlled state waits for acceptance; disabled Rows are skipped.
onRangeChange(detail: CDataGridRangeChangeDetail) => void (CDataGridRangeChangeDetail)Scroll resize configuration or navigation exposes an uncovered desired range.{startIndex, endIndex, visibleStartIndex, visibleEndIndex, requestId, reason, sourceEvent} (CDataGridRangeChangeDetail)Coalesced per animation frame with a monotonic request ID.
onCellActivate(detail: CDataGridCellActivateDetail) => void (CDataGridCellActivateDetail)Enter or double-click activates an enabled noneditable body Cell.{rowKey, columnKey, rowIndex, columnIndex, source, sourceEvent} (CDataGridCellActivateDetail)Does not mutate data.
onCellEditStart(detail: CDataGridCellEditDetail) => void (CDataGridCellEditDetail)Enter F2 typing Backspace Delete or double-click enters an editable Cell.{rowKey, columnKey, rowIndex, columnIndex, editor, previousValue, source, reason, sourceEvent} (CDataGridCellEditDetail)The owned native editor receives focus and grid navigation pauses.
onCellEditCommit(value: string | number | boolean, detail: CDataGridCellEditDetail) => boolean | void (CDataGridCellEditDetail)Enter F2 Tab outside pointer or a replacement editor submits a valid changed value.{rowKey, columnKey, rowIndex, columnIndex, editor, previousValue, source, reason, sourceEvent} (CDataGridCellEditDetail)Returning false or throwing keeps the editor open and invalid; otherwise the editor closes while server Rows remain authoritative.
onCellEditCancel(detail: CDataGridCellEditDetail) => void (CDataGridCellEditDetail)Escape or reactive disabling cancels an active edit.{rowKey, columnKey, rowIndex, columnIndex, editor, previousValue, source, reason, sourceEvent} (CDataGridCellEditDetail)Restores server-rendered Cell content without a commit callback.

Methods

-

CSS

CSS variables to theme the components. Set them on an ancestor or the component itself.

CDataGrid CSS variables

Apply these variables to CDataGrid or one of its ancestors.

VariableTypePurposeDefault
--cui-data-grid-viewport-sizelengthMaximum scroll-viewport block size.Server viewport_size or 400px
--cui-data-grid-row-heightlengthFixed ready-Row and Cell block size.Server row_height or 48px
--cui-data-grid-min-widthlengthHorizontal overflow threshold.Sum of Column widths
--cui-data-grid-backgroundcolorGrid surface.Canvas
--cui-data-grid-foregroundcolorPrimary text.CanvasText
--cui-data-grid-mutedcolorState and secondary text.Accessible CanvasText mix
--cui-data-grid-border-colorcolorRow Column and viewport borders.Adaptive neutral
--cui-data-grid-header-backgroundcolorHeader surface.Adaptive neutral
--cui-data-grid-selected-backgroundcolorSelected Row surface.Adaptive blue
--cui-data-grid-striped-backgroundcolorAlternate Row surface.Subtle neutral
--cui-data-grid-hover-backgroundcolorPointer Row feedback.Subtle Highlight mix
--cui-data-grid-focus-colorcolorActive Header and Cell outline.Highlight
--cui-data-grid-radiuslengthViewport corners.0.625rem

Attributes

HTML attributes defined on the components that you can refer to for CSS, inspection, and testing. Read-only.

CDataGrid attributes

AttributeElementTypeMeaning
roleNative tablegridExposes one composite data grid.
aria-rowcountNative tableintegerReports logical Rows plus the Header Row.
aria-colcountNative tableintegerReports logical Column count.
aria-rowindexHeader and supplied Rowspositive integerReports exact one-based logical position.
aria-colindexHeaders and Cellspositive integerReports exact one-based Column position.
aria-sortSorted Headerascending | descending | absentReflects accepted sort direction.
aria-selectedSupplied Rowboolean-string | absentReflects accepted selection when selection is enabled.
data-row-keySupplied Row and CellsstringExposes stable Row identity.
data-column-keyHeader and CellsstringExposes stable Column identity.
data-row-indexSupplied Row and Cellsnonnegative integerExposes zero-based logical Row position for owned navigation.
data-column-indexHeader and Cellsnonnegative integerExposes zero-based Column position for owned navigation.
data-selectedSupplied Rowpresent | absentReflects accepted selection for styling.
data-pendingRootpresent | absentMarks a desired range outside the supplied window.
data-selectingRootpresent | absentMarks an active mouse drag-selection gesture.
data-editableRoot and editable Cellspresent | absentMarks that editing is available.
data-editingRoot and active Cellpresent | absentMarks the active edit session.
data-editorEditable CellCDataGridEditor (CDataGridEditor)Reflects the owned editor kind.
data-stateRootready | loading | empty | errorReflects settled server output state.
tabindexViewport Header or Cell0 | -1Maintains one composite page Tab stop.

Selectors

Selectors for the DOM nodes in the components that you can use for CSS, inspection, and testing.

CDataGrid selectors

SelectorElementPurpose
[data-citry-ui-part="data-grid"]Root divState reflections attrs and theme destination.
[data-citry-ui-part="toolbar"]Optional toolbar wrapperApplication controls before the viewport.
[data-citry-ui-part="status"]Visually hidden polite live regionAccepted sort and selection announcements.
[data-citry-ui-part="viewport"]Scroll divHorizontal and vertical scroll ownership.
[data-citry-ui-part="table"]Native table GridSemantic and keyboard owner.
[data-citry-ui-part="caption"]Optional native captionSupplementary visible description.
[data-citry-ui-part="header"]theadHeader Row group.
[data-citry-ui-part="header-row"]Header trExact Header Row position.
[data-citry-ui-part="header-cell"]thNavigable sortable Column Header.
[data-citry-ui-part="sort-indicator"]Decorative spanAccepted sort direction glyph.
[data-citry-ui-part="body"]tbodySupplied Rows spacers and state output.
[data-citry-ui-part="row"]Supplied trStable selection and Row customization.
[data-citry-ui-part="cell"]Supplied tdNavigable application Cell.
[data-citry-ui-part="editor"]Runtime-owned input or selectTemporarily edits one checked Cell value.
[data-citry-ui-part="loading"]Loading tdLocalized loading output.
[data-citry-ui-part="empty"]Empty tdLocalized empty output.
[data-citry-ui-part="error"]Error tdLocalized failure output.
[data-citry-ui-part="state-row"]State trLoading empty or error output.
[data-citry-ui-part="spacer-row"]Presentation trRepresents omitted fixed-height Rows.

Interfaces

Aliases and data shapes referenced above.

Input type aliases

InterfaceDefinition
CClassValuestr | Mapping[str, bool] | Sequence[CClassValue]
CStyleValuestr | Mapping[str, object] | Sequence[CStyleValue]
CDataGridStateLiteral["ready", "loading", "error"]
CDataGridDensityLiteral["comfortable", "compact", "spacious"]
CDataGridSelectionLiteral["none", "single", "multiple"]
CDataGridAlignLiteral["start", "center", "end"]
CDataGridSortDirectionLiteral["asc", "desc"]
CDataGridSortSourceLiteral["pointer", "keyboard", "client"]
CDataGridSelectionSourceLiteral["pointer", "keyboard", "client"]
CDataGridRangeReasonLiteral["initial", "scroll", "resize", "configuration", "navigation"]
CDataGridEditorLiteral["text", "number", "checkbox", "select"]
CDataGridEditSourceLiteral["pointer", "keyboard"]

CDataGridColumn

FieldTypeDefaultMeaning
keystr-Unique stable Column identity and Row mapping key.
labelstr-Application-localized accessible Header label.
sortablebool-Whether Header activation can request sorting.
widthint-Initial 40 through 2000 CSS-pixel Column width.
alignCDataGridAlign (CDataGridAlign)-Logical Cell text alignment.
header_attrsMapping[str, object] | None-Copied allowed Header attributes.
cell_attrsMapping[str, object] | None-Copied allowed attributes merged into every Cell in the Column.
editablebool-Enables the built-in Cell editor for this Column.
editorCDataGridEditor (CDataGridEditor)-Selects text number checkbox or select control.
editor_optionsSequence[CDataGridEditOption]-Supplies unique application-localized select options.
editor_attrsMapping[str, str | int | float | bool] | None-Adds checked kind-specific attributes such as min max step maxlength and placeholder.

CDataGridCell

FieldTypeDefaultMeaning
valueobject-Escaped or component-like server Cell output.
attrsMapping[str, object] | None-Copied allowed attributes merged after Column Cell attributes.
editablebool | None-Overrides the Column editing policy for this Cell.

CDataGridEditOption

FieldTypeDefaultMeaning
valuestr-Unique submitted select value.
labelstr-Application-localized visible option label.
disabledbool-Prevents selection of this option.

CDataGridRow

FieldTypeDefaultMeaning
keystr-Unique stable supplied-Row identity.
cellsMapping[str, object | CDataGridCell]-Exact one-to-one mapping for every Column key.
disabledbool-Blocks selection and activation for this Row.
attrsMapping[str, object] | None-Copied allowed Row attributes.

CDataGridSort

FieldTypeDefaultMeaning
keystr-Known sortable Column key.
directionCDataGridSortDirection (CDataGridSortDirection)-Accepted ascending or descending direction.

CDataGridCaptionSlotData

Empty dataclass: {}.

CDataGridToolbarSlotData

Empty dataclass: {}.

CDataGridHeaderSlotData

FieldTypeDefaultMeaning
columnCDataGridColumn-Current Column record.
column_indexint-Zero-based Column position.
sort_directionCDataGridSortDirection | None-Accepted direction or none.
sort_priorityint | None-One-based multi-sort priority or none.

CDataGridCellSlotData

FieldTypeDefaultMeaning
rowCDataGridRow-Current Row record.
columnCDataGridColumn-Current Column record.
cellCDataGridCell-Normalized Cell record.
row_indexint-Zero-based logical Row position.
column_indexint-Zero-based Column position.
selectedbool-Initial accepted supplied-Row selection.

CDataGridLoadingSlotData

Empty dataclass: {}.

CDataGridEmptySlotData

Empty dataclass: {}.

CDataGridErrorSlotData

Empty dataclass: {}.

CDataGridSortChangeDetail

FieldTypeDefaultMeaning
sortlist[dict[str, str]]-Requested ordered sort model.
previousSortlist[dict[str, str]]-Accepted model before the request.
columnKeystr-Activated Column key.
directionCDataGridSortDirection | None-Requested direction or none when cleared.
sourceCDataGridSortSource-Pointer keyboard or client cause.
sourceEventobject | None-Native source Event.

CDataGridSelectionChangeDetail

FieldTypeDefaultMeaning
selectedlist[str]-Requested or committed selected supplied-Row keys.
previousSelectedlist[str]-Accepted selection before the request.
changedlist[str]-Keys whose selection changed.
rowKeystr | None-Directly activated Row key.
selectedRowbool | None-Requested state of the directly activated Row.
controlledbool-Whether client selected owns the model.
sourceCDataGridSelectionSource-Pointer keyboard or client cause.
sourceEventobject | None-Native source Event.

CDataGridRangeChangeDetail

FieldTypeDefaultMeaning
startIndexint-Desired inclusive logical start.
endIndexint-Desired exclusive logical end.
visibleStartIndexint-Estimated visible inclusive start.
visibleEndIndexint-Estimated visible exclusive end.
requestIdint-Monotonic instance-local request ID.
reasonCDataGridRangeReason-Initial scroll resize configuration or navigation cause.
sourceEventobject | None-Native source Event when available.

CDataGridCellActivateDetail

FieldTypeDefaultMeaning
rowKeystr-Activated Row key.
columnKeystr-Activated Column key.
rowIndexint-Zero-based logical Row position.
columnIndexint-Zero-based Column position.
sourcekeyboard | pointer-Activation cause.
sourceEventobject-Native source Event.

CDataGridCellEditDetail

FieldTypeDefaultMeaning
rowKeystr-Edited Row key.
columnKeystr-Edited Column key.
rowIndexint-Zero-based logical Row position.
columnIndexint-Zero-based Column position.
editorCDataGridEditor-Active native control kind.
previousValuestr | float | bool-Server-authored value at edit start.
sourceCDataGridEditSource-Keyboard or pointer entry source.
reasonstr-Entry commit or cancellation reason.
sourceEventobject-Native source Event.

Translation keys

Catalog keys used by this family. An explicit component input or slot listed in Override takes precedence over the catalog for that instance.

CDataGrid translation keys

KeyPurposeVariablesOverrideBrowser updates
citry-ui-data-grid-loadingLabels the loading state.None.loading_labelStable $c-tr text follows client locale changes.
citry-ui-data-grid-emptyLabels the empty state.None.empty_labelStable $c-tr text follows client locale changes.
citry-ui-data-grid-errorLabels the error state.None.error_labelStable $c-tr text follows client locale changes.
citry-ui-data-grid-sort-ascendingAnnounces accepted ascending sorting.column: strsort_ascending_label with {column}One-shot i18n.tr() writes the live region after acceptance.
citry-ui-data-grid-sort-descendingAnnounces accepted descending sorting.column: strsort_descending_label with {column}One-shot i18n.tr() writes the live region after acceptance.
citry-ui-data-grid-sort-clearedAnnounces accepted cleared sorting.column: strsort_cleared_label with {column}One-shot i18n.tr() writes the live region after acceptance.
citry-ui-data-grid-selected-oneAnnounces one selected supplied Row.None.selected_one_labelOne-shot i18n.tr() writes the live region after commit or acceptance.
citry-ui-data-grid-selectedAnnounces multiple selected supplied Rows.count: strselected_label with {count}One-shot i18n.tr() writes the live region after commit or acceptance.
citry-ui-data-grid-editNames the runtime-owned editor.column: stredit_label with {column}One-shot i18n.tr() applies when an editor is created.
citry-ui-data-grid-editingAnnounces edit entry.column: strediting_label with {column}One-shot i18n.tr() writes the live region.
citry-ui-data-grid-edit-submittedAnnounces a submitted edit request.column: stredit_submitted_label with {column}One-shot i18n.tr() writes the live region.
citry-ui-data-grid-edit-cancelledAnnounces edit cancellation.column: stredit_cancelled_label with {column}One-shot i18n.tr() writes the live region.
citry-ui-data-grid-edit-invalidAnnounces native validation or callback rejection.column: stredit_invalid_label with {column}One-shot i18n.tr() writes the live region.