How-To: Scrolling Programmatically to a Text Position

Scrolling in TX Text Control .NET is pretty easy when working with text fields. However, if you want to scroll to a certain text position, it is not that easy. The following method shows a way how to do that.

Please note: The textPosition value is zero-based (like the Selection.Start or the InputPosition.TextPosition property) and has to be increased by 1 to get the requested character of the TextCharCollection. If the increased value is greater than the number of TextChars of the TextCharCollection, the Y-coordinate of the last line in the TextControl will be used to set the TextControl.ScrollLocation.

private void scrollToTextPosition(int textPosition)
    Point newScrollLocation = textControl1.ScrollLocation;
    if (textPosition & 1 <= textControl1.TextChars.Count)
        newScrollLocation = new Point(0, textControl1.TextChars[textPosition + 1].Bounds.Y);
        newScrollLocation = new Point(0, textControl1.Lines[textControl1.Lines.Count].TextBounds.Y);
    textControl1.ScrollLocation = newScrollLocation;
Private Sub scrollToTextPosition(ByVal textPosition As Integer)
    Dim newScrollLocation As Point = textControl1.ScrollLocation
    If textPosition + 1 <= textControl1.TextChars.Count Then
        newScrollLocation = New Point(0, textControl1.TextChars(textPosition + 1).Bounds.Y)
        newScrollLocation = New Point(0, textControl1.Lines(textControl1.Lines.Count).TextBounds.Y)
    End If
    textControl1.ScrollLocation = newScrollLocation
End Sub