Link to home
Start Free TrialLog in
Avatar of Matrix1000
Matrix1000

asked on

How to search for text in a textbox In Reverse?

I have a snippet of code to search a RichTextBox, but it only searches it forward. How can I search it in reverse too?  
I would like it search to the bottom and then ask to start from the top again with a messagebox.

Thanks for a code example !


Public Sub Find()
        Dim StartPosition As Integer = -1
 
        If RichTextBox1.SelectionLength = 0 Then
            StartPosition = RichTextBox1.Text.IndexOf(cmbSearchText.Text, RichTextBox1.SelectionStart)
        Else
            StartPosition = RichTextBox1.Text.IndexOf(cmbSearchText.Text, RichTextBox1.SelectionStart + RichTextBox1.SelectionLength)
        End If
 
        If StartPosition <> -1 Then
            RichTextBox1.[Select](StartPosition, cmbSearchText.Text.Length)
            RichTextBox1.Focus()
            RichTextBox1.ScrollToCaret()
        Else
            MessageBox.Show("String: " + cmbSearchText.Text.ToString() + " not found", "No Matches", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
            Return
        End If
    End Sub

Open in new window

Avatar of ZachSmith
ZachSmith
Flag of United States of America image

Use the function LastIndexOf()
ASKER CERTIFIED SOLUTION
Avatar of ZachSmith
ZachSmith
Flag of United States of America image

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
cant you use the .Contains() method?
If richTextBox1.Text.Contains("xyz") Then

Open in new window

Yes, but you can't use that to find multiple instances.. For example the string:

This is my string

Would return true for .Contains("i"), but you can't tell where the "i" is or how many "i"s there are.
SOLUTION
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
That's a good approach!