Setting the current cursor line in a .NET TextBox

In .NET, you can easily get the line number of the location of the TextBox cursor (that is, the "current line") using GetLineFromCharIndex and SelectionStart :

 var currentLine = textBox1.GetLineFromCharIndex(textBox1.SelectionStart); 

Is there a "clean / native" way to set the cursor in the given TextBox line (ie set the "current line")? Or, at least, a “clean / native” way to get the char index of the first character of a given string (something like getCharIndexFromLine , opposite the function I set earlier)?

A way to do this would be to iterate over the first N-1 elements of the Lines TextBox property and summarize their lengths plus the lengths of the lines. Any other idea?

+6
source share
2 answers

The GetFirstCharIndexFromLine() function is GetFirstCharIndexFromLine() :

 int myLine = 3; int pos = textBox1.GetFirstCharIndexFromLine(myLine); if (pos > -1) { textBox1.Select(pos, 0); } 
+4
source

This was the best I could come up with:

 private void SetCursorLine(TextBox textBox, int line) { int seed = 0, pos = -1; line -= 1; if(line == 0) pos = 0; else for (int i = 0; i < line; i++) { pos = textBox.Text.IndexOf(Environment.NewLine, seed) + 2; seed = pos; } if(pos != -1) textBox.Select(pos, 0); } 

If you want to start counting lines at 0, delete the line -= 1; segment line -= 1; .

+1
source

Source: https://habr.com/ru/post/949916/


All Articles