Boris Boskovic
Boris Boskovic

Reputation: 343

RichTextBox Select multiple appearances of the same word

I created Notepad like app using C# (Windows Forms), and I want to add Find functionality, which will highlight every appearance of a search term. However I don't know how to add to existing selection so I end up with highlighting only the last appearances of a search term. This is my code:

Regex regex = new Regex(args.searchTerm);
MatchCollection matches = regex.Matches(richTextArea.Text);
foreach (Match match in matches)
{
    richTextArea.Select(match.Index, match.Length);
}

So, what should I do?

Upvotes: 2

Views: 1380

Answers (2)

Omar_abdelslam
Omar_abdelslam

Reputation: 17

Multiple search and select what was searched for, this code worked for me without any errors.

 int Timer;
 private void button5_Click(object sender, EventArgs e)
    {
        string r = textR.Text;
        richTextBox1.SelectAll();
        richTextBox1.SelectionBackColor = richTextBox1.BackColor;
        string txt = textF.Text;
        int ff = 0;

        for (int af = 0; ff != -1; af++)
        {
            ff = richTextBox1.Find(textF.Text, Timer + 1, RichTextBoxFinds.None);
            if (ff != -1)
            {
                Timer = ff;
                richTextBox1.Select(ff, txt.Length);
                richTextBox1.SelectionBackColor = Color.Yellow;
                richTextBox1.SelectedText = r;
            }
        }
        Timer = 0;
    }

Other Solution

string s1 = textBox2.Text;

         if (s1.Length > 0)
         {
             int startpos = richTextBox1.Find(textBox2.Text, a + 1, RichTextBoxFinds.NoHighlight);
             int leanth = s1.Length;
             a = startpos;
             MessageBox.Show(startpos.ToString());
             richTextBox1.Focus();
             richTextBox1.Select(startpos, textBox2.Text.Length);
         }

         else
             MessageBox.Show("This Text Or Characters is Not Find");

Upvotes: 0

TaW
TaW

Reputation: 54433

Decide what you want:

  • You can only select one range of characters.

  • You can however highlight multiple ranges (by setting e.g. their BackColor, i.e. by adding e.g. a richTextArea.SelectionBackColor = Color.Yellow in the loop)..

Example:

enter image description here

private void searchTextBox_TextChanged(object sender, EventArgs e)
{
    Regex regex = new Regex(searchTextBox.Text);
    MatchCollection matches = regex.Matches(richTextArea.Text);
    richTextArea.SelectAll();
    richTextArea.SelectionBackColor = richTextArea.BackColor;
    foreach (Match match in matches)
    {
        richTextArea.Select(match.Index, match.Length);
        richTextArea.SelectionBackColor = Color.Yellow;
    }
}

Upvotes: 4

Related Questions