user422831 user422831 - 1 year ago 93
C# Question

Highlight all searched word in richtextbox

In my

, if i have written as below.

This is my pen,

his pen is beautiful.

Now I search word "is" then
output would be as below.

All "is" should be highlighted.


Answer Source

What about:

static class Utility {
    public static void HighlightText(this RichTextBox myRtb, string word, Color color) {  

       if (word == string.Empty)

       int s_start = myRtb.SelectionStart, startIndex = 0, index;

       while((index = myRtb.Text.IndexOf(word, startIndex)) != -1) {
           myRtb.Select(index, word.Length);
           myRtb.SelectionColor = color;

           startIndex = index + word.Length;

       myRtb.SelectionStart = s_start;
       myRtb.SelectionLength = 0;
       myRtb.SelectionColor = Color.Black;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download