question

CharlesHe-MSFT avatar image
0 Votes"
CharlesHe-MSFT asked ·

TextBox. GetLineIndexFromCharacterIndex returns -1 when passing in large text

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-wpf
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

AlexLi-MSFT avatar image
0 Votes"
AlexLi-MSFT answered ·

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.

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.