w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do you search for a string in a rich text box and highlight all found or highlight each line?

Your code has a few problems.

  • You call the search and selection routines only once per button click, so only one occurrence can be found each time. If you want to highlight all occurrences you need to create a loop

  • You undo each change in the FindMyText method. That makes no sense. You may want to clear all selections before you search something new, but not while searching

  • You set the selection color before setting the selection. This will do nothing, at best..

Here is a version which stores all positions in a list and supports two buttons to go forward and backward through the list..:

List<int> found = null;

private void cb_findAll_Click(object sender, EventArgs e)
{
    int cursorPos = rtb.SelectionStart; 
    clearHighlights(rtb);
    found = FindAll(rtb, txtSearch.Text, 0);
    HighlightAll(rtb, Color.Red, found, txtSearch.Text.Length);
    rtb.Select(cursorPos, 0);   
}

private void cb_findNext_Click(object sender, EventArgs e)
{
    int pos = -1;
    for (int f = 0; f < found.Count; f++)
        if (found[f] > rtb.SelectionStart) { pos = found[f]; break; }
    if (pos >= 0) rtb.Select(pos, txtSearch.Text.Length);
    rtb.ScrollToCaret();
}

private void cb_findPrev_Click(object sender, EventArgs e)
{
    int pos = -1;
    for (int f = 0; f < found.Count; f++)
        if (found[f] >= rtb.SelectionStart) { if (f >= 1) pos =
found[f - 1]; break; }
    if (pos >= 0) rtb.Select(pos, txtSearch.Text.Length);
    rtb.ScrollToCaret();
}

public List<int> FindAll(RichTextBox rtb, string txtToSearch, int
searchStart)
{
    List<int> found = new List<int>();
    if (txtToSearch.Length <= 0) return found;

    int pos= rtb.Find( txtToSearch, searchStart, RichTextBoxFinds.None);
    while (pos >= 0)
    {
        found.Add(pos);
        pos = rtb.Find(txtToSearch, pos + txtToSearch.Length,
RichTextBoxFinds.None);
    }
    return found;
}

public void HighlightAll(RichTextBox rtb, Color color, List<int>
found, int length)
{
    foreach (int p in found)
    {
        rtb.Select(p, length);
        rtb.SelectionColor = color;
    }
}

void clearHighlights(RichTextBox rtb)
{
    int cursorPos = rtb.SelectionStart;    // store cursor
    rtb.Select(0, rtb.TextLength);         // select all
    rtb.SelectionColor = rtb.ForeColor;    // default text color
    rtb.Select(cursorPos, 0);              // reset cursor
}


private void txtSearch_TextChanged(object sender, EventArgs e)
{
    found = new List<int>();         // clear list
    clearHighlights(rtb);            // clear highlights
}
private void rtb_TextChanged(object sender, EventArgs e)
{
    found = new List<int>();
    clearHighlights(rtb);
}

Note how small each piece of code is!





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.