spectreconsole/spectre.console · error · InvalidOperationException
Cannot add new columns to table with existing rows.
Error message
Cannot add new columns to table with existing rows.
What it means
Thrown by Table.AddColumn when at least one row already exists. Like the Grid, the table fixes its column schema once the first row is added; adding columns afterward would break row/column alignment guarantees.
Source
Thrown at src/Spectre.Console/Widgets/Table/Table.cs:94
/// </summary>
public Table()
{
_columns = [];
Rows = new TableRowCollection(this);
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="column">The column to add.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public Table AddColumn(TableColumn column)
{
ArgumentNullException.ThrowIfNull(column);
if (Rows.Count > 0)
{
throw new InvalidOperationException("Cannot add new columns to table with existing rows.");
}
_columns.Add(column);
return this;
}
/// <inheritdoc/>
protected override Measurement Measure(RenderOptions options, int maxWidth)
{
ArgumentNullException.ThrowIfNull(options);
var measurer = new TableMeasurer(this, options);
// Calculate the total cell width
var totalCellWidth = measurer.CalculateTotalCellWidth(maxWidth);
// Calculate the minimum and maximum table width
var measurements = _columns.Select(column => measurer.MeasureColumn(column, totalCellWidth));View on GitHub (pinned to 0acc92fada)
Solutions
- Register all columns before adding any rows.
- Reorder builder code so AddColumn calls precede AddRow calls.
- Build a new Table instance if the schema must change after data is present.
Example fix
// before
var table = new Table();
table.AddRow("a", "b");
table.AddColumn(new TableColumn("Col1")); // throws
// after
var table = new Table();
table.AddColumn(new TableColumn("Col1"));
table.AddColumn(new TableColumn("Col2"));
table.AddRow("a", "b"); Defensive patterns
Strategy: validation
Validate before calling
// Ensure all AddColumn calls happen before any AddRow.
if (table.Rows.Count > 0) throw new InvalidOperationException("Cannot add columns after rows"); Prevention
- Build the column schema fully before adding rows.
- Refactor to avoid interleaving AddColumn and AddRow calls.
When it happens
Trigger: Calling AddColumn on a Table after one or more AddRow calls.
Common situations: Data-driven table building where rows are populated in a loop before columns are finalized, or refactoring that moved AddColumn calls after row creation.
Related errors
- Cannot add new columns to grid with existing rows.
- The number of row columns are greater than the number of gri
- Ratio must be equal to or greater than 1
- Minimum size must be equal to or greater than 1
- Size must be equal to or greater than 1
AI-assisted analysis of spectreconsole/spectre.console@0acc92fada (2026-08-13).
Data as JSON: /api/errors/1c2a91169d554214.
Report an issue: GitHub.