Introduction
In this article, I am going to explain how to search and highlight text in Rich TextBox in a Windows Forms app using Visual Studio 2017.
STEP 1 - Start the Project
Let's create a new project using Visual Studio 2017.
Select New Project--->Visual C#-->Windows Forms App (.NET Framework), give your project a name and click OK.
This action creates a WinForms project with a default form and you should see the Windows designer.
STEP 2 - Drag and Drop Control
Let's add a control to the form by dragging it from Toolbox and dropping it to the form. You will see a Rich TextBox 1 is added to the form. This control is now available to you in the code behind.
Search and Highlight Text
The textbox will be used to enter the search string and on the button click, we will be performing a search in the Rich TextBox. Add a class variable called 'start'. This variable will be the start position within the control text from where you need to begin searching.
Also, add another variable called 'IndexofsearchText' to hold position/index of the search string in the Rich TextBox. RTF stands for Rich Text Format, and this describes a certain file type where text formatting is encoded with special character embedded in the text. Programs such as Microsoft Word can use RTF documents.
Now, let's add another control to the form by dragging the other control from Toolbox to the form. You may also want to change the properties of the other controls.
Change the text of button and label control to what you like.
STEP 3 - Coding
Follow the coding given below,
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- string[] words = textBox1.Text.Split(',');
- foreach(string word in words)
- {
- int startindex = 0;
- while(startindex < richTextBox1.TextLength)
- {
- int wordstartIndex = richTextBox1.Find(word, startindex, RichTextBoxFinds.None);
- if (wordstartIndex != -1)
- {
- richTextBox1.SelectionStart = wordstartIndex;
- richTextBox1.SelectionLength = word.Length;
- richTextBox1.SelectionBackColor = Color.Yellow;
- }
- else
- break;
- startindex += wordstartIndex + word.Length;
- }
- }
- }
-
- private void button2_Click(object sender, EventArgs e)
- {
- richTextBox1.SelectionStart = 0;
- richTextBox1.SelectAll();
- richTextBox1.SelectionBackColor = Color.White;
- }
- }
STEP 4 - Compile and Run
Now, simply compile and run the aplication.
Copy and paste the paragraph in Rich TextBox. Enter the text in the Textbox you need to search and highlight in the paragraph. After clicking the search Button, the Text entered in the Textbox will be searched and highlighted in the paragraph.
Summary
In this basic article, you saw how to search and highlight text in Rich TextBox control. Hope you found this article interesting. For any feedback, please post it as a comment at the bottom of this article. Thank you!