To search for text in a RichTextBox control in C#, you can use the Find
method. Here’s an example of how you can search for text in a RichTextBox:
private void SearchText(string searchText)
{
int startPos = richTextBox1.SelectionStart + richTextBox1.SelectionLength;
int index = richTextBox1.Find(searchText, startPos, RichTextBoxFinds.None);
if (index != -1)
{
richTextBox1.SelectionStart = index;
richTextBox1.SelectionLength = searchText.Length;
richTextBox1.Focus();
}
else
{
// Text not found
MessageBox.Show("Text not found.");
}
}
In this example, the SearchText
method takes a searchText
parameter, which is the text you want to search for. It starts the search from the current selection position in the RichTextBox.
The Find
method is called on the richTextBox1
control and searches for the specified text starting from the startPos
. The RichTextBoxFinds.None
option is used to perform a simple search without any special options.
If the text is found, the method sets the selection in the RichTextBox to highlight the found text and gives focus to the control. If the text is not found, it displays a message box indicating that the text was not found.
You can call the SearchText
method by passing the text you want to search as a parameter. For example:
SearchText("example text");
This will search for the text “example text” in the RichTextBox control.