tui-cs/Terminal.Gui · error · ArgumentOutOfRangeException

Must be non-negative

Error message

Must be non-negative

What it means

GetNextMatchingItem performs type-ahead navigation in a list/table/tree. The currentIndex parameter represents the currently selected item index; a negative value is invalid because there is no item at a negative position. Pass null when there is no current selection.

Source

Thrown at Terminal.Gui/Views/CollectionNavigation/CollectionNavigatorBase.cs:42

        {
            lock (_lock)
            {
                _searchString = value;
            }

            OnSearchStringChanged (new (value));
        }
    }

    /// <inheritdoc/>
    public int TypingDelay { get; set; } = 500;

    /// <inheritdoc/>
    public int? GetNextMatchingItem (int? currentIndex, char keyStruck)
    {
        if (currentIndex.HasValue && currentIndex < 0)
        {
            throw new ArgumentOutOfRangeException (nameof (currentIndex), @"Must be non-negative");
        }

        if (!char.IsControl (keyStruck))
        {
            // maybe user pressed 'd' and now presses 'd' again.
            // a candidate search is things that begin with "dd"
            // but if we find none then we must fallback on cycling
            // d instead and discard the candidate state
            var candidateState = "";
            TimeSpan elapsedTime;
            string currentSearchString;

            lock (_lock)
            {
                elapsedTime = DateTime.Now - _lastKeystroke;
                currentSearchString = _searchString;
            }

View on GitHub (pinned to 2e47b11478)

Solutions

  1. Pass null instead of -1 when there is no current selection.
  2. Clamp the index to >= 0 before calling.
  3. Check HasValue and >= 0 before invoking.

Example fix

// before
navigator.GetNextMatchingItem(list.SelectedItem - 1, key);
// after
navigator.GetNextMatchingItem(list.SelectedItem > 0 ? list.SelectedItem - 1 : null, key);
Defensive patterns

Strategy: validation

Validate before calling

int? idx = current < 0 ? null : current;
navigator.GetNextMatchingItem (idx, key);

Type guard

static bool IsValidNavIndex (int? i) => i is null || i >= 0;

Prevention

When it happens

Trigger: Calling navigator.GetNextMatchingItem(-1, 'a'); or passing a computed currentIndex that went negative (e.g. SelectedItem - 1 when SelectedItem was 0).

Common situations: Off-by-one in selection math; passing -1 as a 'no selection' sentinel instead of null; decrementing an index below zero before calling.

Related errors


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