New to Telerik UI for WinForms? Download free 30-day trial

Positioning

The positioning feature in the RadRichTextBox is used to navigate through document's content and to get information about the document's elements at a specific position. The RadDocument uses the positioning to track the movement of the caret and to control the selection.

The positioning is implemented via the DocumentPosition class. This class can be used by the developer to programmatically control the positioning or the selection. DocumentPosition offers methods, such as MoveToNextWord(), MoveToPreviousWord(), MoveToCurrentLineStart/End() and so on, which will navigate to the given document element. In order to get information about the element at a given position you can use several methods such as GetCurrentSpanBox(), GetCurrentParagraphBox(), GetCurrentSectionBox() and so on.

DocumentPosition also redefines equality and comparison operators for more convenience, when you should find whether the DocumentPosition is before or after another position in the natural flow of the document. By default RadRichTextBox moves Document.CaretPosition using arrow keys or on mouse click. DocumentPosition can also be obtained by giving the coordinates of a point in the document using the method DocumentPosition.SetPosition.

You can manage the caret position for a specific RadDocument by either accessing its CaretPosition property, which is of type DocumentPosition, or by creating a new instance of the DocumentPosition class and associating it with the desired RadDocument.

When using the CaretPosition property you are directly managing the caret position in the RadDocument . By using the DocumentPosition class you can create instances of several positions inside the document without changing the current caret position.

CaretPosition property

Here is an example of how to use the CaretPosition property to get the current word.

string currentSpanText = this.radRichTextBox1.Document.CaretPosition.GetCurrentSpanBox().Text;

Dim currentSpanText As String = Me.RadRichTextBox1.Document.CaretPosition.GetCurrentSpanBox().Text

DocumentPosition class

An alternative of using the CaretPosition property is to create an instance of the DocumentPosition class. Here is the same example from the previous chapter done with an instance of the DocumentPosition class.

DocumentPosition position = new DocumentPosition(this.radRichTextBox1.Document);
string currentSpanText1 = position.GetCurrentSpanBox().Text;

Dim position As DocumentPosition = New DocumentPosition(Me.RadRichTextBox1.Document)
Dim currentSpanText1 As String = position.GetCurrentSpanBox().Text

In this article