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
        Else
            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)
        HTMLopt.rtb.ScrollToCaret()
        HTMLopt.rtb.Focus()

What exactly is it doing/not doing?

Have you tried:

RichTextBox1.Text.Replace("ThisString","ThatString")

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

Try doing the replacement after the search is done, probably right after line 21.

Hi,
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)
Else
    HTMLopt.rtb.Text.Replace(txtSearchTerm.Text,txtReplacement.Text)
End if

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

Clipboard.SetText(txtReplacementText.Text)
StartPosition = Instr(StartPosition,HTMLopt.rtb.text, txtSearchTerm.text,SearchType)
Do Until StartPosition = 0
    HTMlopt.rtb.Select(StartPosition-1, txtSearchterm.text.length)
    HTMLopt.rtb.ScrolltoCaret()
    application.DoEvents()
    HTMLopt.rtb.paste()
    Instr(StartPosition,HTMLopt.rtb.text, txtSearchTerm.text,SearchType)
Next