Hi all.
im writing function to find and replace the string. Im using 2 textbox's one for keyword which is to find and one to to replace. im having having two buttons btnfindnext and btnreplace. if i click on replace button it should select the text first and agin if i click on the same it should replace the string. and if i click on findnext it should select the next keyword in the document and if again btn replace is clicked it should replace the selected text.
Like in Ms word

thanks

Dani AI

Generated

A compact, robust pattern that matches the Word-like behavior requested by : FindNext highlights the next occurrence; Replace acts as "first click selects, second click replaces", and after a replacement the next match is automatically highlighted. This fixes two issues seen above: used String.Replace (which replaces every occurrence) and was right to persist an index but the replace logic must act on the currently selected text, not the next match.

' Put these members and handlers in the form class (example control names shown)
Private _lastPos As Integer = 0
Private _currentFind As String = ""
Private _caseSensitive As Boolean = False

Private Sub btnFindNext_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFindNext.Click
    Dim findText = txtFind.Text
    If String.IsNullOrEmpty(findText) Then Return

    If findText <> _currentFind Then
        _currentFind = findText
        _lastPos = 0
    End If

    Dim cmp = If(_caseSensitive, StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase)
    Dim idx As Integer = txtDoc.Text.IndexOf(findText, _lastPos, cmp)
    If idx = -1 Then
        MessageBox.Show(findText & " not found")
        _lastPos = 0
    Else
        txtDoc.SelectionStart = idx
        txtDoc.SelectionLength = findText.Length
        txtDoc.Focus()
        _lastPos = idx + findText.Length
    End If
End Sub

Private Sub btnReplace_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnReplace.Click
    Dim findText = txtFind.Text
    If String.IsNullOrEmpty(findText) Then Return

    Dim cmp = If(_caseSensitive, StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase)

    If txtDoc.SelectionLength > 0 AndAlso String.Equals(txtDoc.SelectedText, findText, cmp) Then
        Dim start = txtDoc.SelectionStart
        txtDoc.SelectedText = txtReplace.Text
        txtDoc.SelectionStart = start
        txtDoc.SelectionLength = txtReplace.Text.Length
        _lastPos = start + txtReplace.Text.Length

        Dim nextIdx = txtDoc.Text.IndexOf(findText, _lastPos, cmp)
        If nextIdx <> -1 Then
            txtDoc.SelectionStart = nextIdx
            txtDoc.SelectionLength = findText.Length
            txtDoc.Focus()
            _lastPos = nextIdx + findText.Length
        Else
            MessageBox.Show("No more matches")
            _lastPos = 0
        End If
    Else
        btnFindNext.PerformClick()
    End If
End Sub

Notes: reset _lastPos whenever the search term changes or the user edits the document; IndexOf skips overlapping matches (use a Regex with a lookahead if overlapping matches are required); use SelectedText for single replacements instead of String.Replace when only the current match should be changed. This pattern preserves expected selection and continues searching from the correct position.

Recommended Answers

All 5 Replies

Try this:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox3.Text = "The quick brown fox jumps over the lazy dog."
    End Sub

    Private Sub FindButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindButton.Click
        Dim idx As Integer = 0
        idx = TextBox3.Text.IndexOf(TextBox1.Text, idx)
        If idx = -1 Then
            MessageBox.Show(TextBox1.Text & " is not in Textbox3")
        Else
            TextBox3.SelectionStart = idx
            TextBox3.SelectionLength = TextBox1.Text.Length
            TextBox3.Focus()
        End If
    End Sub

    Private Sub ReplaceButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReplaceButton.Click
        If TextBox3.Text.Contains(TextBox1.Text) Then
            TextBox3.Text = TextBox3.Text.Replace(TextBox1.Text, TextBox2.Text)
        Else
            MessageBox.Show(TextBox1.Text & " is not in Textbox3")
        End If
    End Sub

End Class

It has 3 textboxes and 2 buttons.

Thnks wayne,
But ur code will search only for fisrt instance of keword and if i click on replace it is replaceing all the instance of key word. if i keep on clicking findnext button it should select and highlight the keyword untill txtend is reached. and when user click on replcae it has to replace the selected text and also it should highlight the next instance of keword in the document if there.
I think its clear to you. please help me out.

Hi,
To search all the instance of keyword, you should explicitly save the last search index.

For this u can use the Variable

Dim iLastIndex as Integer

    Private Sub FindButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindButton.Click
        Dim idx As Integer = iLastIndex
        idx = TextBox3.Text.IndexOf(TextBox1.Text, idx)
        If idx = -1  Then
            MessageBox.Show(TextBox1.Text & " is not in Textbox3")
        Else
            TextBox3.SelectionStart = idx
            TextBox3.SelectionLength = TextBox1.Text.Length
            TextBox3.Focus()
            iLastIndex = TextBox1.Text.Length + idx
        End If
    End Sub

To replace, First u have to select the Text first then replace it.

Dim idx As Integer = iLastIndex
        idx = TextBox3.Text.IndexOf(TextBox1.Text, idx)
        If idx = -1 Then
            MessageBox.Show(TextBox1.Text & " is not in Textbox3")
        Else
            TextBox3.SelectionStart = idx
            TextBox3.SelectionLength = TextBox1.Text.Length
            TextBox3.Focus()
            iLastIndex = idx + TextBox2.Text.Length
            TextBox3.SelectedText = TextBox2.Text
            TextBox3.SelectionStart = idx
            TextBox3.SelectionLength = TextBox2.Text.Length
        End If

The same code to find and Last Three lines for replace.

Also at one stage find will go to end of the file at that time you should reset the iLastIndex variable to 0

Thank you.
But your code is replacing the next keyword not selected keyword.

the code is correct but it will not highlight the similer text present two time in sentenc.mean that onece it find the text the same text is enlighted for next time

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.