spectreconsole/spectre.console · error · InvalidOperationException

Cannot add new columns to grid with existing rows.

Error message

Cannot add new columns to grid with existing rows.

What it means

Thrown by Grid.AddColumn when at least one row already exists. The grid fixes its column count once the first row is added, so adding more columns afterward is structurally forbidden to keep rows consistent.

Source

Thrown at src/Spectre.Console/Widgets/Grid.cs:67

    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public Grid AddColumn()
    {
        AddColumn(new GridColumn());
        return this;
    }

    /// <summary>
    /// Adds a column to the grid.
    /// </summary>
    /// <param name="column">The column to add.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public Grid AddColumn(GridColumn column)
    {
        ArgumentNullException.ThrowIfNull(column);

        if (_rows.Count > 0)
        {
            throw new InvalidOperationException("Cannot add new columns to grid with existing rows.");
        }

        // Only pad the most right cell if we've explicitly set a padding.
        _padRightCell = column.HasExplicitPadding;

        _columns.Add(column);

        return this;
    }

    /// <summary>
    /// Adds a new row to the grid.
    /// </summary>
    /// <param name="columns">The columns to add.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public Grid AddRow(params IRenderable[] columns)
    {
        ArgumentNullException.ThrowIfNull(columns);

View on GitHub (pinned to 0acc92fada)

Solutions

  1. Add all columns before adding any rows.
  2. Restructure the builder code so column setup precedes row population.
  3. If dynamic columns are needed later, construct a new Grid instance instead of mutating an existing one.

Example fix

// before
var grid = new Grid();
grid.AddRow(new Text("a"), new Text("b"));
grid.AddColumn(); // throws

// after
var grid = new Grid()
    .AddColumn().AddColumn()
    .AddRow(new Text("a"), new Text("b"));
Defensive patterns

Strategy: validation

Validate before calling

// Ensure all AddColumn calls happen before any AddRow.
if (grid.Rows.Any()) throw new InvalidOperationException("Cannot add columns after rows");

Prevention

When it happens

Trigger: Calling AddColumn after one or more AddRow calls on the same Grid instance.

Common situations: Building a grid procedurally where rows are added in a loop before all columns are registered, or refactoring that reorders AddColumn calls after row creation.

Related errors


AI-assisted analysis of spectreconsole/spectre.console@0acc92fada (2026-08-13). Data as JSON: /api/errors/968b8081cd537534. Report an issue: GitHub.