dotnet/wpf · error · ArgumentOutOfRangeException

SR.DataGrid_ColumnIndexOutOfRange

Error message

SR.DataGrid_ColumnIndexOutOfRange

What it means

DataGridColumnCollection.SetItem throws ArgumentOutOfRangeException with DataGrid_ColumnIndexOutOfRange when replacing a column using an index that is >= Count or negative. Only indices of existing columns can be replaced.

Solutions

  1. Validate 0 <= index && index < Columns.Count before assignment
  2. Recompute indices after any add/remove of columns
  3. Use Contains/the column reference instead of raw indices where possible

Example fix

// before
grid.Columns[i] = newColumn;
// after
if (i >= 0 && i < grid.Columns.Count) grid.Columns[i] = newColumn;
Defensive patterns

Strategy: validation

Validate before calling

if (index < 0 || index >= grid.Columns.Count)
    throw new ArgumentOutOfRangeException(nameof(index));

Try / catch

try { grid.Columns[i] = col; }
catch (ArgumentOutOfRangeException) { grid.Columns.Add(col); }

Prevention

When it happens

Trigger: dataGrid.Columns[index] = column with index outside [0, Count-1]; off-by-one calculations using Count instead of Count-1; index taken from an external mapping after columns were removed.

Common situations: Stale column indices cached before columns were added/removed; loops using <= Count; user-supplied index not validated.

Related errors


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/ec830c7303488794. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/DataGridColumnCollection.cs:66

            if (DisplayIndexMapInitialized)
            {
                ValidateDisplayIndex(item, item.DisplayIndex, true);
            }

            base.InsertItem(index, item);
            item.CoerceValue(DataGridColumn.IsFrozenProperty);
        }

        protected override void SetItem(int index, DataGridColumn item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item), SR.DataGrid_NullColumn);
            }

            if (index >= Count || index < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.DataGrid_ColumnIndexOutOfRange, item.Header));
            }

            if (item.DataGridOwner != null && this[index] != item)
            {
                throw new ArgumentException(SR.Format(SR.DataGrid_InvalidColumnReuse, item.Header), nameof(item));
            }

            if (DisplayIndexMapInitialized)
            {
                ValidateDisplayIndex(item, item.DisplayIndex);
            }

            base.SetItem(index, item);
            item.CoerceValue(DataGridColumn.IsFrozenProperty);
        }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {

View on GitHub (pinned to 81131a70a4)