Skip to main content

How to: Select Text Programmatically

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

document.LoadDocument("Documents//Grimm.docx", DocumentFormat.OpenXml);
DocumentPosition myStart = document.CreatePosition(69);
DocumentRange myRange = 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.

document.LoadDocument("SelectionCollection.docx", DocumentFormat.OpenXml);
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 });