Find and Highlight text by code

2 posts, 1 answers
  1. Tommaso
    Tommaso avatar
    5 posts
    Member since:
    Oct 2012

    Posted 04 Oct 2012 Link to this post

    Q1 2012
    VS 2010

    The following snippet does not run.

    private void HightlightText(string textToHighlight)
    {
        DocumentTextSearch search = new DocumentTextSearch(this.radRichTextBox.Document);
        foreach (var textRange in search.FindAll(textToHighlight))
        {
            this.radRichTextBox.Document.Selection.AddSelectionStart(textRange.StartPosition);
            this.radRichTextBox.Document.Selection.AddSelectionStart(textRange.EndPosition);
            this.radRichTextBox.ChangeTextHighlightColor(Color.Red);
        }
    }


    How can I highlight with red color all the occurrences of the text?

    Tommaso
  2. Answer
    Svett
    Admin
    Svett avatar
    728 posts

    Posted 08 Oct 2012 Link to this post

    Hi Tommaso,

    Thank you for writing.

    You can use the following code snippet to select the desired words in the RadRichTextBox:
    private void HightlightText(string textToHighlight)
    {
        DocumentTextSearch search = new DocumentTextSearch(this.radRichTextBox1.Document);
        foreach (var textRange in search.FindAll(textToHighlight))
        {
            this.radRichTextBox1.Document.Selection.AddSelectionStart(textRange.StartPosition);
            this.radRichTextBox1.Document.Selection.AddSelectionEnd(textRange.EndPosition);
            this.radRichTextBox1.ChangeTextHighlightColor(Color.Red);
        }
    }

    I hope this helps.

    Greetings,
    Svett
    the Telerik team
    RadControls for WinForms Q2'12 release is now live! Check out what's new or download a free trial >>
  3. UI for WinForms is Visual Studio 2017 Ready
Back to Top