Link to home
Start Free TrialLog in
Avatar of davidlam8888

asked on

how can I replace text in richtextbox?

Hi, all
How can I replace TEXT in RichTEXT box??
I can not find to method in Richtexbox to replace TEXT?
Can anyone provide some coding?
Avatar of Mikal613
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial has introduced a number of changes to the way you access the RichTextBox's properties. SelUnderline, SelBold, SelStrikethrough etc are now available in the


property. For example, in, use


instead of


Use this:

        Dim strFind As String = "stringtofind"
        Dim iPos As Integer = RichTextBox1.Find(strFind)
        RichTextBox1.Select(iPos, strFind.Length)
        RichTextBox1.SelectedText = "stringtoreplace"

try this:

assuming the string you want to search in richtextbox1 is written in textBox1 and the button1 is the button which will tell you the index ...

set your richTextBox.HideSelection property to false( which is true by default)  so that this code can show you the occurences of the required text..

Dim position As Integer = 0 ' in the declaration section of your form class

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click

       Dim index As Integer = RichTextBox1.Text.IndexOf(TextBox1.Text, position)' get the index of next occurance

       If (index > -1) Then' if the word is found
           RichTextBox1.Select(index, TextBox1.Text.Length) ' select and show the found text in the richtextbox

' You can also remove the line below to have the "FIND" Feature only instead of "FIND and REPLACE" feature
          RichTextBox1.SelectedText = "New Word" 'put your word(s) that you want tyo replace

           position = index + TextBox1.Text.Length        'update the position        

           MessageBox.Show("The string " & TextBox1.Text & " cannot be found")
        End If

   End Sub