# Dynamic Columns in a Blazor Grid

URL: https://flexcoreui.com/demo/grid/dynamic-columns  
Section: Data Grid  
Controls: GridControl, GridColumn  
Keywords: dynamic columns, auto-generate columns, ExpandoObject, data annotations, dictionary rows

A Blazor grid whose columns follow the data: read them from ExpandoObject keys, or generate them from data annotations with AutoGenerateColumns.

## Documentation

### Column

| Name | Type | Default | Description |
|---|---|---|---|
| Field | string | "" | The key the grid reads a cell by. On an IDictionary<string, object> or IDictionary<string, object?> row it is the entry key, matched exactly first and then case-insensitively; on any other row it is a public instance property matched case-insensitively through a cached compiled getter. There is no nested-path support, so A.B is looked up as one name and reads as null. It is also the header when HeaderText is null, the key of the column's sort and filter state, and the identity used when columns are added, removed or replaced. |
| HeaderText | string? | null | The caption. Null shows Field itself (DisplayHeader); an empty string is an intentional blank header. |
| Type | ColumnType | ColumnType.Text | Picks the editor, the filter-row operators and their comparison, the sort-dialog labels, the plain-number and password display and the best-fit measure; the values are below. It does not change how a sort compares: GridSortKeyComparer compares the raw values by their own runtime type. Only Date and CheckBox change the default alignment, so a Number column stays left-aligned unless TextAlign is set, which is why the example sets it. |
| Format | string? | null | A .NET format string applied with the current culture when the raw value is IFormattable (N2, C2, yyyy-MM-dd). Without it a Number cell shows the plain invariant digits with no grouping, and a Date editor uses MM/dd/yyyy. Also the format of the aggregate footer, of the date picker in a row editor, and the number format of an exported xlsx cell. |
| DisplayFormatter | Func<object, string>? | null | Text for a non-null cell value. When set it is the display text, the search and filter text and the exported value, ahead of Format and Type; sorting still compares the raw value. |
| DisplayField | string? | null | A second field read through the same accessor. Its value stands in for the raw value in the display, search and filter text unless it is null, DBNull or blank; sorting still reads Field. |
| Formula | string? | null | A per-row expression evaluated instead of reading Field. Bracketed names such as [Qty] * [UnitPrice] go through the field accessor; bare names are matched against the row's dictionary keys or public properties. The result feeds the display text, the filter text and the export. |
| IsPrimaryKey | bool | false | Set by AutoGenerateColumns for a [Key] property. A generated row editor disables the cell for it. |
| AllowEditing | bool | true | AutoGenerateColumns sets it false for a [Key], [Editable(false)] or [ReadOnly(true)] property and for one without a public setter; that is what keeps Item # and Extended read-only in the batch example. |

### Column types

| Name | Description |
|---|---|
| Text | The default. The cell shows the value's ToString; the filter row defaults to Contains and offers the full text operator list; the editor is a text box; the sort dialog offers A to Z. |
| Password | Shown as one * per character; the row editor uses a password input; filters treat it as text. |
| Number | Without Format the cell shows the plain invariant digits with no grouping. The filter row offers Equals, DoesNotEqual, the four comparisons, IsEmpty and IsNotEmpty and compares as decimal; the editor uses inputmode=decimal and a native number input only with ShowNumericSpinner; best fit measures the column as numeric. The default alignment is still Left. |
| Date | Right-aligned by default. The row editor is a DatePickerControl with Format or MM/dd/yyyy, the batch editor an input of type date; the filter row offers the Number operator set and compares as dates; the sort dialog offers Oldest to Newest. |
| Boolean | Edited with a CheckBoxControl in the row editor and without an in-cell text editor in batch mode; the filter row offers Equals, DoesNotEqual, IsEmpty and IsNotEmpty and compares as bool. The display cell has no special case, so it shows True or False as text, left-aligned. |
| CheckBox | Renders a check box in the cell, and a click on an editable cell toggles the value in place. Centered by default; only an explicit TextAlign.Right overrides that. Exports write 1 or 0. Filters and editors behave as Boolean. A CheckBox column with an empty Field is the selection check-box column. |

### Row shapes

| Name | Description |
|---|---|
| IDictionary<string, object> / IDictionary<string, object?> | Tried first: TryGetValue with the exact key, then a scan of the entries with a case-insensitive key match. Sorting, filtering, search and export all read through the same accessor. An edit writes row[Field] = value; on the non-nullable shape a null is stored as an empty string. A row-editor clone copies the entries rather than properties. |
| ExpandoObject | Is an IDictionary<string, object?>, so it takes the dictionary path. A key missing on a row, as LeadTimeDays is before the switch is on, reads as null and shows an empty cell. A typed batch edit stores the editor's string as the entry: there is no property type to convert to. |
| Class or record with public properties | A public instance property named Field, case-insensitive, no indexers, read through a compiled getter cached per row type and field. An edit converts the text to the property type before writing. A getter that throws reads as null. |
| Nested path (Address.City) | Not supported. The whole string is looked up as one key or property name and reads as null. Flatten the row or use a Template. |
| DataRow / DataRowView | No special handling. A DataRow is neither a dictionary nor a type with a property per column, so every Field reads as null. Project the table into dictionaries or objects first. |

### Grid

| Name | Type | Default | Description |
|---|---|---|---|
| AutoGenerateColumns | bool | false | Builds one column per public readable property of TValue, as listed below, once per grid instance. An explicit GridColumn with the same Field replaces the generated one; extra explicit columns follow the generated set. |
| ColumnHeaderBands | IReadOnlyList<GridColumnHeaderBand>? | null | Band descriptors for the one-level parent header. A band that lists a field in Fields wins over that column's own HeaderBand. |
| AvailableColumns | IEnumerable<ChooseColumnDescriptor>? | null | With AutoGenerateColumns off and no GridColumn declared, each descriptor with a Field becomes a transient column (Field, Header, Visible) so the header row is not empty. Otherwise it is the schema of the Choose Columns dialog. |
| DataSource | IEnumerable<TValue>? | null | The rows. The example swaps the list inside the update scope together with the column list, so the flush render reads both. |
| EditSettingsRef | EditSettings? | null | The editing settings object. The annotations example sets AllowEditing and Mode = Batch, so the generated columns whose AllowEditing stayed true edit in the cell. |
| AllowCellFormulas | bool | false | With it on, a string cell value that starts with = is evaluated as a formula when the cell is read. |

### Methods

| Name | Type | Description |
|---|---|---|
| BeginUpdate() | void | Increments the update depth. While it is above zero the column-registration channel drops its renders, so columns registering or disposing inside the window do not paint; input, selection and batch-edit renders are not gated. Nesting counts, and a BeginUpdate without its EndUpdateAsync keeps column renders suppressed until the grid is disposed. |
| EndUpdateAsync(IEnumerable<string>? finalColumnOrder = null) | Task | At depth zero it returns at once. Otherwise it decrements, and only the outermost call flushes: it stores finalColumnOrder, cancels a pending one-shot render suppression, marks auto widths pending, queues one render and awaits a completion that OnAfterRenderAsync sets once no column render is queued at depth zero. Without an order, new fields append and fields not listed keep their relative order after the listed ones. |
| SuspendRedraw(IEnumerable<string>? finalColumnOrder = null) | ColumnUpdateScope | Calls BeginUpdate and returns a scope whose DisposeAsync calls EndUpdateAsync(finalColumnOrder), so await using balances the pair even when the mutation throws. The page passes the new field list every time, so an added column lands where the first row's key order puts it. |
| ColumnUpdateScope.DisposeAsync() | ValueTask | Wraps EndUpdateAsync(order) in a ValueTask. The scope has no other member; a second disposal reaches the depth-zero no-op. |

## Examples

### Dynamic

```razor
@using System.Dynamic
@using System.Text.RegularExpressions
@using Fx.ControlKit
@using Fx.ControlKit.Grid

<GridControl @ref="_grid"
             TValue="ExpandoObject"
             DataSource="@_rows"
             Height="340px"
             AllowSelection="true"
             AllowSorting="true"
             AllowFiltering="true"
             ShowSearchBar="true"
             ShowRowCountInFooter="true">
    <GridColumnsBase>
        @foreach (var col in _columns)
        {
            <GridColumn @key="col.Field"
                        Field="@col.Field"
                        HeaderText="@col.Header"
                        Width="@(col.Field == "Description" ? "260px" : col.IsNumber ? "110px" : "130px")"
                        Type="@(col.IsNumber ? ColumnType.Number : ColumnType.Text)"
                        Format="@col.Format"
                        TextAlign="@(col.IsNumber ? TextAlign.Right : TextAlign.Left)" />
        }
    </GridColumnsBase>
</GridControl>
<p class="result">@_rows.Count.ToString("N0") rows · @_columns.Count columns: @string.Join(" · ", _columns.Select(c => c.Header))</p>
```

```csharp
private sealed record DynamicColumn(string Field, string Header, bool IsNumber, string? Format);

private readonly SelectionItem[] _sizes = { new("50", "50 rows"), new("500", "500 rows"), new("2000", "2,000 rows") };

private GridControl<ExpandoObject>? _grid;

private List<ExpandoObject> _rows = [];

private List<DynamicColumn> _columns = [];

private int _rowCount = 500;

private bool _leadTime;

protected override void OnInitialized()
{
    _rows = BuildRows(_rowCount, _leadTime);
    _columns = ColumnsFrom(_rows);
}

private Task SetRowCountAsync(int count)
{
    _rowCount = count;
    return ReloadAsync();
}

private Task SetLeadTimeAsync(bool on)
{
    _leadTime = on;
    return ReloadAsync();
}

private async Task ReloadAsync()
{
    var rows = BuildRows(_rowCount, _leadTime);
    var columns = ColumnsFrom(rows);
    if (_grid is null) { _rows = rows; _columns = columns; return; }
    await using (_grid.SuspendRedraw(columns.Select(c => c.Field)))
    {
        _rows = rows;
        _columns = columns;
    }
}

private static List<ExpandoObject> BuildRows(int count, bool leadTime)
{
    var groups = new[] { "Flights", "Hotels", "Tours", "Transfers", "Insurance" };
    var rand = new Random(55);
    var list = new List<ExpandoObject>(count);
    for (int i = 1; i <= count; i++)
    {
        dynamic row = new ExpandoObject();
        row.Code = $"IT-{(1000 + i):D4}";
        row.Description = $"Catalog item {i}, {groups[i % groups.Length].ToLowerInvariant()}";
        row.Group = groups[i % groups.Length];
        row.Status = (i % 4 == 0) ? "Pending" : "Active";
        row.Rate = Math.Round((decimal)(rand.NextDouble() * 250 + 20), 2);
        if (leadTime) row.LeadTimeDays = 1 + (i * 7) % 30;
        list.Add(row);
    }
    return list;
}

private static List<DynamicColumn> ColumnsFrom(List<ExpandoObject> rows)
{
    if (rows.Count == 0) return [];
    var first = (IDictionary<string, object?>)rows[0];
    return first.Select(kv => new DynamicColumn(
        kv.Key,
        Humanize(kv.Key),
        kv.Value is decimal or int or double,
        kv.Value switch { decimal => "N2", int => "N0", _ => null })).ToList();
}

private static string Humanize(string key)
    => System.Text.RegularExpressions.Regex.Replace(key, "(?<=[a-z])(?=[A-Z])", " ");
```

### Annotations

```razor
@using System.ComponentModel
@using System.ComponentModel.DataAnnotations
@using Fx.ControlKit.Grid

<GridControl DataSource="@_annotatedRows"
             TValue="AnnotatedGridItem"
             AutoGenerateColumns="true"
             Height="300px"
             AllowSorting="true"
             AllowFiltering="true"
             EditSettingsRef="@_editSettings" />
```

```csharp
// Columns from data annotations (moved here from Frozen columns, 2026-10-20)
public sealed class AnnotatedGridItem
{
    [Key]
    [Display(Name = "Item #", Order = 0, GroupName = "Identity")]
    public int Id { get; set; }

    [Display(Name = "SKU", Order = 1, GroupName = "Identity")]
    public string Code { get; set; } = "";

    [DisplayName("Product description")]
    public string Description { get; set; } = "";

    [Display(Name = "Unit price", Order = 2, GroupName = "Amounts")]
    [DisplayFormat(DataFormatString = "{0:C2}")]
    public decimal UnitPrice { get; set; }

    [Display(Name = "Extended", Order = 3, GroupName = "Amounts")]
    [DisplayFormat(DataFormatString = "{0:C2}")]
    [Editable(false)]
    public decimal Total { get; set; }

    [Display(AutoGenerateField = false)]
    public string InternalCode { get; set; } = "";
}

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

private List<AnnotatedGridItem> _annotatedRows = BuildAnnotated();

private static List<AnnotatedGridItem> BuildAnnotated() =>
    Enumerable.Range(1, 12).Select(i =>
    {
        var price = 15.50m + (i % 25) * 4.25m;
        return new AnnotatedGridItem
        {
            Id = i, Code = $"SKU-{i:D5}", Description = $"Travel package #{i}",
            UnitPrice = price, Total = (10 + (i * 7) % 150) * price, InternalCode = $"INTERNAL-{i}"
        };
    }).ToList();
```

