Find all and Replace all using VB

Aeros05 21 Reputation points
2021-05-27T13:22:18.943+00:00

Hi
i was trying to create an app just like the notepad function which has the find all and replace all method

here's the code I'm still working on

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    RichTextBox1.Find(TextBox1.Text, 0, RichTextBoxFinds.None)

    RichTextBox1.Focus()



End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    RichTextBox1.SelectedText = TextBox2.Text
End Sub

End Class

Developer technologies Windows Forms
Developer technologies VB
{count} votes

Accepted answer
  1. JasonDaurison 116 Reputation points
    2021-05-27T14:17:56.517+00:00

    You can try using this code:

    This is for the Replace All function:

    If Not txtSearchWord.Text = "" Then
                If RichTextBox1.Text.Contains(txtSearchWord.Text) Then
                    RichTextBox1.Text = Replace(RichTextBox1.Text, txtSearchWord.Text, txtReplaceWord.Text)
                    Exit Sub
                Else
                    MessageBox.Show("The specified text [" & txtSearchWord.Text & "] was not found.", "Failed Search", _
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    txtSearchWord.Text = ""
                    txtSearchWord.Focus()
                    Exit Sub
                End If
            End If
            MessageBox.Show("No search text specified.", "Invalid Search", _
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    

    And this is for the Find All function:

    Static Start As Integer = -1
            Dim Index As Integer
    
                Index = RichTextBox1.Text.IndexOf(txtSearchWord.Text, Start + 1)
    
            If Not Index = -1 Then
                RichTextBox1.Focus()
                RichTextBox1.SelectionStart = Index
                RichTextBox1.SelectionLength = txtSearchWord.Text.Length
                RichTextBox1.ScrollToCaret()
                Start = Index
            Else
                MessageBox.Show("Found all the instances of [" & txtSearchWord.Text & "]", "End Search")
                Start = -1
            End If
    

    This code assumes that the RichTextBox is named: RichTextBox1, and there are two textboxes named: txtSearchWord and txtReplaceWord.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.