Scrolling programmatically to a Text Position

Technical Articles > How-To Guide

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.

[C#]
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);
    }
    else
    {
        newScrollLocation = new Point(0, textControl1.Lines[textControl1.Lines.Count].TextBounds.Y);
    }
    textControl1.ScrollLocation = newScrollLocation;
}
[Visual Basic]
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)
    Else
        newScrollLocation = New Point(0, textControl1.Lines(textControl1.Lines.Count).TextBounds.Y)
    End If
    textControl1.ScrollLocation = newScrollLocation
End Sub