How to implement "Search Previous" in a "Find Keyword" Windows Form in C#

233 Views Asked by At

I have a Log Window in my c# application. I have implemented a Find Keyword Feature in the form, it searches for all matching text in the RichTextBox. Now I want to build a feature to search the Next and Previous matches throughout the RichTextBox.

The code for the FindNext is

try
{
    if (start_search_point < log_textbox.Text.Length && start_search_point != -1)
    {
        log_textbox.SelectionBackColor = highlight_all_color;
        log_textbox.Find(search_keyword, start_search_point, RichTextBoxFinds.WholeWord);
        log_textbox.SelectionBackColor = Color.Honeydew;

        if (start_search_point + search_keyword.Length < log_textbox.Text.Length)
            start_search_point = log_textbox.Text.IndexOf(search_keyword, start_search_point + search_keyword.Length);
        else
            start_search_point = 0;
    }
    else
    {
        start_search_point = 0;
    }
}
catch (Exception ex)
{
    MDIParent.thisMdiObj.txtLog.Invoke(new Action(() => MDIParent.thisMdiObj.txtLog.AppendText(DateTime.Now.ToString() + " : " + ex.Message + "=>" + ex.StackTrace.ToString() + Environment.NewLine)));
}

Can anyone help me with the FindPrevious part? I cannot figure out the logic for this one.

1

There are 1 best solutions below

7
On

How about creating MatchCollection and work with it?

MatchCollection matches = new Regex().Matches(search_keyword);

int currentIndex = 0;

And then just use currentIndex to get elements from your collection-

if(currentIndex > 0) --currentIndex;   // get previous search result
matches[currentIndex];

Example: enter image description here