I can't believe these properties aren't already natively implemented. Come on Microsoft... we do live in the year 2007 you know!!
I know that you can do this using P/Invoke and SendMessage but i wanted a nice managed way of finding
the current line and column of the Caret position in a multiline TextBox.
After a bit of experimenting i've come up with this extended class:
public class TextBoxEx : TextBox
{
public TextBoxEx()
{ }
public void GoTo(int line, int column)
{
if (line < 1 || column < 1 || this.Lines.Length < line)
return;
this.SelectionStart = this.GetFirstCharIndexFromLine(line - 1) + column - 1;
this.SelectionLength = 0;
}
public int CurrentColumn
{
get { return this.SelectionStart - this.GetFirstCharIndexOfCurrentLine() + 1; }
}
public int CurrentLine
{
get { return this.GetLineFromCharIndex(this.SelectionStart) + 1; }
}
}
Hope you find it usefull. If anyone knows a better way do let me know.
UPDATE: With a bit of help from Andrej this is a better and shorter version with set method too.