I have a replace button which has to replace a word that is searched inside the richtextbox(rtb).But the code is not working, help me identify my mistake. Thank you

 If HTMLopt.rtb.SelectedText.Length <> 0 Then
            HTMLopt.rtb.SelectedText = txtReplacementText.Text
        End If

        Dim StartPosition As Integer = HTMLopt.rtb.SelectionStart + 2
        Dim SearchType As CompareMethod

        If chkMatchCase.Checked = True Then
            SearchType = CompareMethod.Binary
            SearchType = CompareMethod.Text
        End If

        StartPosition = InStr(StartPosition, HTMLopt.rtb.Text, txtSearchTerm.Text, SearchType)

        If StartPosition = 0 Then
            MessageBox.Show("String: '" & txtSearchTerm.Text.ToString() & "' not found", "No Matches", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
            Exit Sub
        End If

        HTMLopt.rtb.Select(StartPosition - 1, txtSearchTerm.Text.Length)

When I run this code on the click event of Replace button, the function says it cannot find the string

It looks to me that you're replacing the selected text before you're searching the richtextbox, for an even different text. Is this what you intend?

I intend to search the given text and replace it by the text entered in replacementtext

As far as I can see there are two ways to do this, just use the replace function:

IF Instr(StartPosition,HTMLopt.rtb.text, txtSearchTerm.text,SearchType) = 0 then
    Messagebox.show("String :'" &txtSearchTerm.Text &"' not found", "No Matches", MessageboxButtons.OK, MessageboxIcon.Asterisk)
End if

Or if you fancy scrolling through the textbox and replacing as you go something like this:

StartPosition = Instr(StartPosition,HTMLopt.rtb.text, txtSearchTerm.text,SearchType)
Do Until StartPosition = 0
    HTMlopt.rtb.Select(StartPosition-1, txtSearchterm.text.length)
    Instr(StartPosition,HTMLopt.rtb.text, txtSearchTerm.text,SearchType)
This article has been dead for over six months. Start a new discussion instead.