Windows Forms: How to Search and Highlight Text in a RichTextBox using C#

How to Search and Highlight Text in a RichTextBox using C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "SearchRichTextBox" and then click OK

c# search richtextboxStep 2: Design your form as below

highlight text in richtextbox

Step 3: Add code to handle your form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SearchRichTextBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            //Split a string to arrays
            string[] words = txtSearch.Text.Split(',');
            foreach(string word in words)
            {
                int startIndex = 0;
                while (startIndex < richTextBox.TextLength)
                {
                    //Find word & return index
                    int wordStartIndex = richTextBox.Find(word, startIndex, RichTextBoxFinds.None);
                    if (wordStartIndex != -1)
                    {
                        //Highlight text in a richtextbox
                        richTextBox.SelectionStart = wordStartIndex;
                        richTextBox.SelectionLength = word.Length;
                        richTextBox.SelectionBackColor = Color.Yellow;
                    }
                    else
                        break;
                    startIndex += wordStartIndex + word.Length;
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            //Clear
            richTextBox.SelectionStart = 0;
            richTextBox.SelectAll();
            richTextBox.SelectionBackColor = Color.White;
        }
    }
}

VIDEO TUTORIALS