Skip to main content Skip to footer

Highlight Searched Words in C1Editor

C1Editor is a control that works on the same line as MS word and MS FrontPage. One can search the word by using the find feature of the same. But there might be certain situations when the user wants to highlight all the occurrences of the searched word in the C1Editor. This is similar to the function performed by Google toolbar wherein you search for a topic, navigate to a matching page and clicking on the google toolbar highlight button adds a yellow highlight to all the instances of the search text that appear in the page. This blog discusses approach to the same in C1Editor. The approach adopted is to find the word by going letter by letter through the whole text of the loaded document and then apply formatting by changing it's backcolor. The following code snippet implements the desired behavior. You may add the same on the Button's click event :


        cnt = 0  
        C1Editor1.LoadXml(path & "\\\Tesla.htm")  
        Dim str As String = TextBox1.Text  
        'calculate the lenght of whole text rendered in C1Editor  
        Dim fulltxt_ln As Integer = C1Editor1.Text.Length  
        'calculate the lenght of the word/pharse to be searched  
        Dim findtxt_ln As Integer = str.Length  

        If findtxt_ln > 0 Then  
            For i = 0 To fulltxt_ln Step +1  
                C1Editor1.SelectionStart = C1Editor1.SelectionStart + findtxt_ln  
                If (i + findtxt\_ln) <= fulltxt\_ln Then  
                    'compare the text searched with the substring of the C1Editor  
                    If C1Editor1.Text.Substring(i, findtxt_ln).ToLower = str.ToLower Then  
                        C1Editor1.Select(i, findtxt_ln)  
                        'set the backcolor of each occurrence of the word in C1Editor  
                        C1Editor1.Selection.ApplyStyle("background-color", "lightblue")  
                        cnt = cnt + 1  
                    End If  
                End If  
            Next  
        End If  
        If cnt > 0 Then  
            MessageBox.Show(cnt.ToString + " instances of word found")  
        Else  
            MessageBox.Show("0 instances of the word found")  
        End If

Using the above code, the final output looks like the following : HighlightedWords Refer to the attached sample for complete implementation of the same. Download Sample Note : Since, the search is done letter by letter to find all the occurrences of the word and apply formatting, there may be certain delay and performance issues for very large documents.

MESCIUS inc.

comments powered by Disqus