In addition to properties, the TextBox control exposes two methods for selecting text. You can select some text by using the Select method, whose syntax is shown next:
TextBox1.Select(start, length)
Code language: CSS (css)
The Select method is equivalent to setting the SelectionStart and SelectionLength properties. To select the characters 100 through 105 on the control, call the Select method, passing the values 99 and 6 as arguments:
TextBox1.Select(99, 6)
Code language: VB.NET (vbnet)
As a reminder, the order of the characters starts at 0 (the first character’s index is 0, the second character’s index is 1, and the last character’s index is the length of the string minus 1). If the range of characters you select contains hard line breaks, you must take them into consideration as well. Each hard line break counts for two characters (carriage return and line feed). If the TextBox control contains the string ABCDEFGHI, the following statement will select the range DEFG:
TextBox1.Select(3, 4)
Code language: VB.NET (vbnet)
If you insert a line break every third character and the text becomes the following, the same statement will select the characters DE only:
ABC
DEF
GHI
Code language: VB.NET (vbnet)
In reality, it has also selected the two characters that separate the first two lines, but special characters aren’t displayed and can’t be highlighted. The length of the selection, however, is 4. A variation of the Select method is the SelectAll method, which selects all the text on the control.
Undoing Edits – CanUndo property
An interesting feature of the TextBox control is that it can automatically undo the most recent edit operation. To undo an operation from within your code, you must first examine the value of the CanUndo property. If it’s True, the control can undo the operation; then you can call the Undo method to undo the most recent edit.
An edit operation is the insertion or deletion of characters. Entering text without deleting any is considered a single operation and will be undone in a single step. Even if the user has spent an hour entering text (without making any corrections), you can make all the text disappear with a single call to the Undo method. Fortunately, the deletion of the text becomes the most recent operation, which can be undone with another call to the Undo method. In effect, the Undo method is a toggle. When you call it for the first time, it undoes the last edit operation. If you call it again, the operation is redone it previously undid. The deletion of text can be undone only if no other editing operation has taken place in the meantime. You can disable the redo operation by calling the ClearUndo method, which clears the undo buffer of the control. You should call it from within an Undo command’s event handler to prevent an operation from being redone. In most cases, you should give users the option to redo an operation, especially because the Undo method can delete an enormous amount of text from the control.