Link to home
Start Free TrialLog in
Avatar of fattumsdad
fattumsdad

asked on

Rich Text Box, Search

I am using the following code to search a rich text box:

private void cmdSearch_Click(object sender, EventArgs e)
        {
            // Initialize search feature
            string search = txtSearch.Text;
            richTextBox1.Find(search);
            richTextBox1.Select();
            txtSearch.Clear();
        }

This will find the first instance of whatever word it is that I'm searching for.  How would I search again, from my current position, for another instance of the same word?
Avatar of AaronReams
AaronReams

Something like this should work... of course you'll want to reset last_postion if the text changes or you reach the end of the document.

public int last_position = -1;

private void cmdSearch_Click(object sender, EventArgs e)
       {
            // Initialize search feature
            string search = txtSearch.Text;
            richTextBox1.Find(search, last_postion+1);
            richTextBox1.Select();
            //txtSearch.Clear();
        }
oops... forgot to add this...

last_position = richTextBox1.Find(search, last_postion+1);
ASKER CERTIFIED SOLUTION
Avatar of AaronReams
AaronReams

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of fattumsdad

ASKER

Thanks for the help, I REALLY appreciate it!!!!!!
No problem.  Small bug in that version.  It won't find the word if it is the first (0) position...

This fixes the problem...

            public int last_position = 0;
            public string last_string = "";
            private void button2_Click(object sender, System.EventArgs e)
            {
                  if(this.textBox1.Text != last_string)
                  {
                        last_string = this.textBox1.Text;
                        last_position = 0;
                  }

                  if(last_position == 0)
                        last_position = this.richTextBox1.Find(last_string,RichTextBoxFinds.None);
                  else
                        last_position = this.richTextBox1.Find(last_string,last_position,RichTextBoxFinds.None);

                  if(last_position < 0)
                  {
                        MessageBox.Show("Not found, click again to start from beginning");
                        last_position = 0;
                        return;
                  }

                  this.richTextBox1.Select();
                  this.richTextBox1.Select(last_position, last_string.Length);
                  last_position +=1;
                  
            }


Enjoy!  -Aaron
Great!  Thanks again!!!