There are two ways to manipulate a range of text:
- A text range is selected using TextControl.Select. This selection is changed using the TextControl.Selection property that manipulates the current selection.
- A new Selection object is created and assigned to the TextControl.Selection property.
Most users are going with the first, more obvious approach. A range of text is selected and changed using a sequence of Selection properties:
textControl1.Select(0, 5); textControl1.Selection.Bold = true; textControl1.Selection.Italic = true; textControl1.Selection.Text = "New Text";
This works very reliably and can be used in most scenarios. But this approach has two drawbacks:
- A selection is visible on the screen. The text is visually selected with the transparent blue background in order to be formatted.
- Each change of the selection is counted as a single Undo history step.
In the above code, three undo steps are required to revert to the previous state. So, what if we could modify the Selection virtually before applying to our TextControl instance? This is what the second approach above does.
A new virtual Selection object is created and manipulated using the same properties. After the object is finished, it will be assigned to the Selection property of our TextControl instance.
TXTextControl.Selection sel = new TXTextControl.Selection(); sel.Text = "New Text"; sel.Bold = true; sel.Italic = true; textControl1.Selection = sel;
This is counted as a single Undo step and there is no visible selection background.