tui-cs/Terminal.Gui · error · ArgumentOutOfRangeException

FocusedItem index is out of range

Error message

FocusedItem index is out of range

What it means

Thrown by OptionSelector.FocusedItem setter when CanFocus is true and the supplied value is < 0 or >= the number of CheckBox subviews. FocusedItem maps directly onto a checkbox in the SubViews, so an out-of-range index has no target to focus. Note the guard is skipped (early return) when CanFocus is false, so the throw only occurs in focusable selectors.

Source

Thrown at Terminal.Gui/Views/Selectors/OptionSelector.cs:231

                return 0;
            }

            return HasFocus ? SubViews.OfType<CheckBox> ().ToArray ().IndexOf (Focused) : field;
        }
        set
        {
            if (!CanFocus)
            {
                return;
            }

            field = value;

            CheckBox [] checkBoxes = SubViews.OfType<CheckBox> ().ToArray ();

            if (value < 0 || value >= checkBoxes.Length)
            {
                throw new ArgumentOutOfRangeException (nameof (value), @"FocusedItem index is out of range");
            }

            if (HasFocus)
            {
                checkBoxes [value].SetFocus ();
            }
        }
    }

    /// <inheritdoc/>
    public bool EnableForDesign ()
    {
        AssignHotKeys = true;
        Labels = ["Option 1", "Option 2", "Third Option", "Option Quattro"];

        return true;
    }

View on GitHub (pinned to 2e47b11478)

Solutions

  1. Clamp against the current checkbox count before assigning: selector.FocusedItem = Math.Clamp(idx, 0, checkboxCount - 1);
  2. When rebuilding options, reset FocusedItem to 0 (or a valid index) afterwards.
  3. Treat search/no-match (-1) as 'no focus change' instead of passing it in.

Example fix

// before
selector.FocusedItem = lastFocused; // stale after options changed

// after
var count = selector.SubViews.OfType<CheckBox>().Count();
selector.FocusedItem = count > 0 ? Math.Clamp(lastFocused, 0, count - 1) : 0;
Defensive patterns

Strategy: validation

Validate before calling

int count = selector.SubViews.OfType<CheckBox>().Count();
if (count > 0)
{
    selector.FocusedItem = Math.Clamp(idx, 0, count - 1);
}

Type guard

static bool IsValidFocus(int i, int checkboxCount) => i >= 0 && i < checkboxCount;

Prevention

When it happens

Trigger: Setting FocusedItem after the options/checkboxes changed (items removed), capturing an index from a previous layout, or computing the focused index from a search returning -1. Also setting it before the checkboxes are built.

Common situations: Re-binding the selector's source and reusing a stale focused index; filtering options without clamping focus; off-by-one using the options Count instead of Count-1.

Related errors


AI-assisted analysis of tui-cs/Terminal.Gui@2e47b11478 (2026-08-13). Data as JSON: /api/errors/44d41fba4541392a. Report an issue: GitHub.