Thursday, September 2, 2010

C# Tutorial: Searching words in a text and highlighting them

Here is the code

int index = 0; string temp = richTextBox1.Text; richTextBox1.Text = ""; richTextBox1.Text = temp;

while (index < richTextBox1.Text.LastIndexOf(textBox1.Text))
{
    // Searches the text in a RichTextBox control for a string within a range of text withing the control and with specific options applied to the search.
    richTextBox1.Find(textBox1.Text, index, richTextBox1.TextLength, RichTextBoxFinds.None);
    // Selection Color. This is added automatically when a match is found.
    richTextBox1.SelectionBackColor = Color.Yellow; 
    // After a match is found the index is increased so the search won't stop at the same match again. This makes possible to highlight same words at the same time.
    index = richTextBox1.Text.IndexOf(textBox1.Text, index) + 1; 
}

Or download the solution

2 comments:

  1. Hi.
    You are creating good programs.
    I just need excat how to search from textbox words
    and highlight them but the problem i can't find out how to search any words from textbox and higglight them not in richtextbox but in listbox if it is possible of course.

    I hope you will make a new tutorial how to search words from textbox and add them into listbox.

    I like what you are doing ;)
    Thanks.

    ReplyDelete
  2. Thank you for sharing your video
    i want to say something on this video
    do while (index <= richTextBox1.Text.LastIndexOf(textBox1.Text)) // <=
    because you cant highlight that first world

    ReplyDelete