Back to Devexpress

How to: Select Text Programmatically

windowsforms-6668-controls-and-libraries-rich-text-editor-examples-text-how-to-select-text-programmatically.md

latest2.4 KB
Original Source

How to: Select Text Programmatically

  • Feb 24, 2025

The following example illustrates how to select one or multiple ranges in code.

Select a Single Range

Use the Document.Selection property to select a text. The following code snippet illustrates how you can select a range of 69 positions starting from the position 216 in the document:

View Example

csharp
document.LoadDocument("Grimm.docx", DocumentFormat.Docx);
DocumentPosition myStart = document.CreatePosition(69);
DocumentRange myRange = document.CreateRange(myStart, 216);
document.Selection = myRange;
vb
document.LoadDocument("Grimm.docx", DocumentFormat.Docx)
Dim myStart As DocumentPosition = document.CreatePosition(69)
Dim myRange As DocumentRange = document.CreateRange(myStart, 216)
document.Selection = myRange

Select Multiple Ranges

Add target DocumentRange objects to the SelectionCollection to select multiple ranges, as shown in the code sample below:

csharp
document.LoadDocument("SelectionCollection.docx", DocumentFormat.Docx);
DocumentRange range1 = document.CreateRange(80, 100);
DocumentRange range2 = document.CreateRange(300, 100);
int startPos3 = document.Tables[0].Rows[0].LastCell.ContentRange.Start.ToInt();
DocumentRange range3 = document.CreateRange(startPos3, 100);
DocumentRange range4 = document.CreateRange(720, 100);
document.Selections.Add(new List<DocumentRange>() { range1, range2, range3, range4 });
vb
document.LoadDocument("SelectionCollection.docx", DocumentFormat.Docx)
Dim range1 As DocumentRange = document.CreateRange(80, 100)
Dim range2 As DocumentRange = document.CreateRange(300, 100)
Dim startPos3 As Integer = document.Tables(0).Rows(0).LastCell.ContentRange.Start.ToInt()
Dim range3 As DocumentRange = document.CreateRange(startPos3, 100)
Dim range4 As DocumentRange = document.CreateRange(720, 100)
document.Selections.Add(New List(Of DocumentRange)() From {range1, range2, range3, range4})