To locate a string in the text of the RichTextBox control, use the Find method. The Find method is quite flexible, as it allows you to specify the type of the search, whether it will locate entire words, and so on. The simplest form of this method accepts the search string as an argument and returns the location of the first instance of the word in the text. If the search argument isn’t found, the method returns the value −1.
RichTextBox1.Find(string)
Code language: VB.NET (vbnet)
Another equally simple syntax of the Find method allows you to specify how the control will search for the string:
RichTextBox1.Find(string, searchMode)
Code language: VB.NET (vbnet)
The searchMode argument is a member of the RichTextBoxFinds enumeration, which is shown in Table 4.7.
Table 4.7 – The RichTextBoxFinds Enumeration
Value | Effect |
---|---|
MatchCase | Performs a case-sensitive search. |
NoHighlight | The text found will not be highlighted. |
None | Locates instances of the specified string even if they’re not whole words. |
Reverse | The search starts at the end of the document. |
WholeWord | Locates only instances of the specified string that are whole words. |
Two more forms of the Find method allow you specify the range of the text in which the search will take place:
RichTextBox1.Find(string, start, searchMode)
RichTextBox1.Find(string, start, end, searchMode)
Code language: VB.NET (vbnet)
The arguments start and end are the starting and ending locations of the search (use them to search for a string within a specified range only). If you omit the end argument, the search will start at the location specified by the start argument and will extend to the end of the text.
You can combine multiple values of the searchMode argument with the OR operator. The default search is case-insensitive, covers the entire document, and highlights the matching text on the control. The RichTextBoxPad application’s Find command demonstrates how to use the Find method and its arguments to build a Search & Replace dialog box that performs all the types of text-searching operations you might need in a text-editing application.