1

I have a textbox and if I type "Dog", My application is supposed to replace "Dog" with "Cute Dog". But when I try and run it, lots of text is generated because it is finds "Dog" in "cute dog" that it has just replaced. Here is the code:

txtMain.Text = Microsoft.VisualBasic.Strings.Replace(txtMain.Text, "Dog", "Cute Dog", 1, -1, Constants.vbTextCompare)
            txtMain.Select(txtMain.Text.Length, 0)

this is being triggered on the text changed event.

1

1 Answer 1

3

The reason is that replacing the text like that fires the TextChanged-event again because that ... well ... changes the text of the TextBox. It's not an UI-only event if users change anything on their screen.

Now thats what makes your application write "cute cute dog" then, and with that fires the event again, and again ...

You could introduce a member variable _replacing which is set to true as long as the replacing takes place. When it's done, reset it to false.

Now the only thing you have to do is to jump out of your code when the code is replacing:

If (_replacing) Then
    Return
End If

_replacing = True

txtMain.Text = Microsoft.VisualBasic.Strings.Replace(txtMain.Text, "Dog", "Cute Dog", 1, -1, Constants.vbTextCompare)
        txtMain.Select(txtMain.Text.Length, 0)

_replacing = False

With this, user input is still replaced but the changes from the replacement itself will not trigger the event again.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.