TextBox. GetLineIndexFromCharacterIndex returns -1 when passing in large text

Charles He-MSFT 96 Reputation points Microsoft Employee
2020-03-27T08:34:24.123+00:00

This is a MSDN question asked by moondaddy, the source is TextBox. GetLineIndexFromCharacterIndex returns -1 when passing in large text.

The sample code below calls the GetLineIndexFromCharacterIndex method on the TextBox and it returns -1 when passing in text 55,000 or larger. Is this a bug and is there a work-around for this?

public MainWindow()
{
    InitializeComponent();
    string text = "";
    string path = "problematicFile.txt";

    // This text is added only once to the file.
    if (File.Exists(path))
    { 
        text = System.IO.File.ReadAllText(path);
    }            
    textBox.Text = text;
    var chararcter1 = textBox.Text[56218];
    var chararcter2 = textBox.Text[56325];
    int index1 = textBox.GetLineIndexFromCharacterIndex(56218);
    int index2 = textBox.GetLineIndexFromCharacterIndex(56325);
}

1567747

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Alex Li-MSFT 1,096 Reputation points
    2020-03-27T09:02:41.893+00:00

    Hi,

    Welcome to our Microsoft Q&A platform!

    The reply form Kareninstructor

    There may be, have not tried stuffing that many lines into a TextBox, you could try the following extension method, place into a static class in your project to see if that works.

    Taken from https://stackoverflow.com/questions/15204830/get-index-of-line-from-textbox-c-sharp

    public static int GetLineIndex(this TextBox textbox, int line)
    {
        var text = textbox.Text;
        var thisLine = 0;
        for (var i = 0; i < text.Length; i++)
        {
            if (thisLine == line)
                return i;
    
            if (text[i] == '\n')
                ++thisLine;
        }
    
        throw new ArgumentOutOfRangeException();
    }
    

    Or report this to Microsoft via the feedback button in Visual Studio.

    Since this is WPF your post is being moved to the WPF forum.

    Thanks.

    0 comments No comments