# Dynamic Column Sets in a Blazor Grid

URL: https://flexcoreui.com/demo/grid/column-swap  
Section: Data Grid  
Controls: GridControl, GridColumn  
Keywords: dynamic columns, column sets, runtime columns, column visibility

Change what a Blazor grid shows at runtime: swap its whole column set at once, without remounting it or losing its data and selection.

## Documentation

### Column

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string | "" | The row property the cell reads, through a cached accessor, or the key when the row is a dictionary; a missing or unreadable member gives an empty cell. Also the column's identity: GridColumnsBase replaces a new instance with the same Field in place, SuspendRedraw(order) matches fields by it, and a column without one is not navigable, sortable or editable. |
| HeaderText | string? | null | The caption. Null shows the Field (DisplayHeader); an empty string is a deliberately blank header. A caption renamed through the header menu wins until ClearColumnOverrides(). |
| Width | string? | null | CSS width emitted on the header cell and every data cell. A drag-resize replaces it with a runtime pixel width, which a same-Field replacement instance inherits. Left blank, the grid estimates a width from up to 50 rows of the data source once the columns have settled, outside any BeginUpdate window. |
| MinWidth | string? | null | Emitted as min-width on the data cells, not the header; the floor of the width the grid computes for frozen offsets and column virtualization, and handed to best fit as a bound. A non-pixel value stops column virtualization from resolving the column. |
| MaxWidth | string? | null | The max-width counterpart of MinWidth; when both are set the floor is applied last, as in CSS. |
| Type | ColumnType | ColumnType.Text | Text, Password, Number, Date, Boolean or CheckBox. Picks the filter operators, the editor (check box, date editor, number input), the default alignment and the plain ungrouped display of a Number column without Format. |
| TextAlign | TextAlign? | null | Cell alignment. Null resolves by Type: CheckBox centers, Date right-aligns, everything else left-aligns. On a CheckBox column only Right overrides; Left still centers. |
| HeaderTextAlign | TextAlign | Grid.TextAlign.Left | Caption alignment in the header cell, independent of the cells. The default is TextAlign.Left, written with the Grid. qualifier in the source because the parameter above hides the enum. |
| Format | string? | null | .NET format string applied to an IFormattable value with the current culture, after DisplayFormatter and mapped edit options have had their turn; also used by aggregates and the Excel export. Blank on a Number column means plain ungrouped text. |
| Visible | bool | true | False keeps the column registered, with its sort, filter and column state, but out of the rendered set, keyboard navigation, edit targets and auto-width. A Choose Columns or Hide choice by the user overrides it per field until ClearColumnOverrides(). |
| AllowSorting | bool | true | With the grid's AllowSorting: a header click sorts, the arrow and the menu item show. A column without a Field never sorts. |
| AllowFiltering | bool | true | With the grid's AllowFiltering: the header filter icon, the filter-row cell and the menu filter are offered. |
| AllowEditing | bool | true | Every edit entry, double-click, keyboard, dropdown or generated row editor, also requires EditSettings.AllowEditing, a Field and not IsPrimaryKey; false makes the column read-only while the rest of the row edits. AllowCellDragSelection can keep column drag selection on. The editing parameters themselves are on the Batch editing page. |
| AllowResizing | bool | true | With the grid's AllowResizing: the header gets its resize grip; false also skips the grip's double-click best fit. |
| AllowHiding | bool | true | Whether the header menu may hide the column (never the last visible one, never a grouped one) and whether Choose Columns offers to. |
| Template | RenderFragment<object>? | null | Cell content in place of the value; context is the row, typed as object. Wins over ChildContent. A templated cell counts as an action cell for clicks and as a keyboard edit target. |
| HeaderTemplate | RenderFragment? | null | Replaces the caption span in the header cell; the sort arrow and the filter icon still render after it. |
| ChildContent | RenderFragment<object>? | null | Shorthand for Template, used only while Template is null. |

### Columns base

| Name | Type | Default | Description |
|---|---|---|---|
| ChildContent | RenderFragment? | null | The GridColumn tags, rendered inside a CascadingValue of the container so each column registers in its OnInitialized and unregisters in Dispose; a @foreach here adds and removes columns in place. |
| DebugTag | string? | null | Declared, but only read behind an if (false && …) in OnInitialized, so it never does anything. |

### Columns base props

| Name | Type | Description |
|---|---|---|
| Columns | IReadOnlyList<GridColumn> | The registered columns in display order. A new instance with the same Field replaces the old one at its index and inherits its drag-resize width; a header drag or Choose Columns moves entries; a disposed column is removed by reference. |
| ColumnsGeneration | int | Bumped once per completed registration wave in the container's OnAfterRender and handed to the grid as NotifyColumnsCompleted(generation), which ignores a repeat of the same generation. |

### Methods

| Name | Type | Description |
|---|---|---|
| SuspendRedraw(IEnumerable<string>? finalColumnOrder = null) | ColumnUpdateScope | The exception-safe form of the pair below, await using (grid.SuspendRedraw(fields)) { … }: the scope's constructor calls BeginUpdate(), its DisposeAsync awaits EndUpdateAsync(finalColumnOrder). ColumnUpdateScope is nested in GridControl<TValue>. What this page uses. |
| BeginUpdate() | void | Suspends column-driven grid renders; calls nest, so only the outermost EndUpdateAsync flushes. A bare call must be balanced in a try/finally: a leaked depth suppresses column renders until the grid is disposed. |
| EndUpdateAsync(IEnumerable<string>? finalColumnOrder = null) | Task | When the outermost window closes: re-renders the child content once so added and removed columns converge in place, queues one auto-width pass, and applies finalColumnOrder in the render pass that first has every listed field registered; fields not listed follow in their old relative order, and without an order new fields append. Completes when the batch carrying the final column set has rendered. A call with no open BeginUpdate is a no-op. |

### Events

| Name | Type | Description |
|---|---|---|
| RowSelecting | RowSelectEventArgs<TValue> | Before a row is selected by mouse, keyboard or checkbox toggle. Set Cancel to refuse. Not raised by AutoSelectFirstRow, type-ahead moves or the selection methods. |
| RowSelected | RowSelectEventArgs<TValue> | After a row is selected by mouse, keyboard, checkbox toggle, type-ahead search or AutoSelectFirstRow. Not raised during drag-select or by the selection methods. |
| SelectionChanged | int | After any change to the selected set: click, drag-select, Select All, Clear, the selection methods. The payload is the selected count, rows or cells by Mode. |
| SelectionChangedDetailed | GridSelectionChangedArgs | Same timing, with Count and Source: Pointer, MouseDrag, Keyboard, Programmatic or Unknown. |
| RowDeselecting / RowDeselected | RowSelectEventArgs<TValue> | Declared, but GridControl never raises them. TreeGridControl raises RowDeselected. |

### Args

| Name | Type | Default | Description |
|---|---|---|---|
| Data | TValue? | null | The row. |
| RowIndex | int | 0 | The row's index in the grid's current display order. |
| Cancel | bool | false | Set in RowSelecting to keep the current selection. Ignored by RowSelected. |

## Examples

### Sets

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

<GridControl @ref="_grid"
             TValue="CRow"
             DataSource="@_rows"
             Height="340px"
             AllowSelection="true"
             AllowResizing="true"
             AllowSorting="true"
             ShowRowCountInFooter="true"
             EditSettingsRef="@_editSettings"
             EventsRef="@_events">
    <GridColumnsBase>
        @foreach (var col in _currentColumns)
        {
            <GridColumn @key="col.Field"
                        Field="@col.Field"
                        HeaderText="@col.Header"
                        Width="@col.Width"
                        Visible="@col.Visible"
                        AllowEditing="@col.Editable" />
        }
    </GridColumnsBase>
</GridControl>
<p class="result">@_activeLayout set: @_currentColumns.Count(c => c.Visible) of @_currentColumns.Count columns visible@(_selected is null ? "" : $" · selected row {_selected}")</p>
```

```csharp
public class CRow
{
    public string Code { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public string Category { get; set; } = string.Empty;
    public string Supplier { get; set; } = string.Empty;
    public string BookingRef { get; set; } = string.Empty;
    public decimal Qty { get; set; }
    public decimal Price { get; set; }
    public decimal Total => Qty * Price;
}

private readonly SelectionItem[] _layouts = { new("Default", "Default"), new("Purchasing", "Purchasing"), new("Minimal", "Minimal") };

private GridControl<CRow>? _grid;

private List<CRow> _rows = [];

private string _activeLayout = "Default";

private List<ColumnSpec> _currentColumns = [];

private string? _selected;

private readonly EditSettings _editSettings = new() { AllowEditing = true, Mode = EditMode.Batch };

private readonly GridControlEvents<CRow> _events = new();

protected override void OnInitialized()
{
    _rows =
    [
        new CRow { Code = "HT-110", Description = "Hotel, double room per night", Category = "Hotels", Supplier = "Casa Lumiar Riverside", BookingRef = "BK-2041", Qty = 14, Price = 145.00m },
        new CRow { Code = "FL-210", Description = "Return flight, economy", Category = "Flights", Supplier = "Tejo Skyline Charters", BookingRef = "BK-2042", Qty = 24, Price = 189.00m },
        new CRow { Code = "TF-310", Description = "Airport transfer, shuttle bus", Category = "Transfers", Supplier = "Alfama Coach Lines", BookingRef = "BK-2043", Qty = 2, Price = 320.00m },
        new CRow { Code = "TR-410", Description = "Sintra palaces day tour", Category = "Tours", Supplier = "Quinta Azul Day Tours", BookingRef = "BK-2044", Qty = 24, Price = 68.50m },
        new CRow { Code = "IN-510", Description = "Group travel insurance", Category = "Insurance", Supplier = "Harborline Travel Cover", BookingRef = "BK-2045", Qty = 24, Price = 34.50m },
        new CRow { Code = "RL-610", Description = "Rail pass, Lisbon to Porto", Category = "Rail", Supplier = "Ribeira Rail Tours", BookingRef = "BK-2046", Qty = 24, Price = 42.00m }
    ];

    _events.RowSelected = EventCallback.Factory.Create<RowSelectEventArgs<CRow>>(this, args => _selected = args.Data?.Code);
    _events.RowDeselected = EventCallback.Factory.Create<RowSelectEventArgs<CRow>>(this, _ => _selected = null);

    _currentColumns = ColumnsFor("Default");
}

private async Task ApplyLayoutAsync(string layoutName)
{
    _activeLayout = layoutName;
    var columns = ColumnsFor(layoutName);
    if (_grid is null) { _currentColumns = columns; return; }
    await using (_grid.SuspendRedraw(columns.Select(c => c.Field)))
    {
        _currentColumns = columns;
    }
}

private static List<ColumnSpec> ColumnsFor(string layoutName)
    => layoutName switch
    {
        "Purchasing" =>
        [
            new ColumnSpec { Field = nameof(CRow.Code), Header = "Item Code", Width = "90px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.Description), Header = "Description", Width = "220px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.Supplier), Header = "Supplier", Width = "200px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.BookingRef), Header = "Booking Ref", Width = "100px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.Price), Header = "Unit Price", Width = "100px", Visible = true, Editable = true },
            new ColumnSpec { Field = nameof(CRow.Category), Header = "Category", Width = "120px", Visible = false }
        ],
        "Minimal" =>
        [
            new ColumnSpec { Field = nameof(CRow.Code), Header = "Code", Width = "100px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.Description), Header = "Description", Width = "300px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.Total), Header = "Total Cost", Width = "140px", Visible = true, Editable = false }
        ],
        _ => // Default
        [
            new ColumnSpec { Field = nameof(CRow.Code), Header = "Item Code", Width = "90px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.Description), Header = "Description", Width = "240px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.Category), Header = "Category", Width = "130px", Visible = true },
            new ColumnSpec { Field = nameof(CRow.Qty), Header = "Qty", Width = "80px", Visible = true, Editable = true },
            new ColumnSpec { Field = nameof(CRow.Price), Header = "Price", Width = "100px", Visible = true, Editable = true },
            new ColumnSpec { Field = nameof(CRow.Total), Header = "Total", Width = "110px", Visible = true, Editable = false }
        ]
    };

// Data/BenchModels.cs
public sealed class ColumnSpec
{
    public string Field { get; set; } = string.Empty;
    public string Header { get; set; } = string.Empty;
    public string Width { get; set; } = "120px";
    public bool Visible { get; set; } = true;
    public bool Editable { get; set; }
}
```

