Monday, March 19, 2012

Replace Text in a TextBox

Everyone has probably used or at least seen the find and replace feature in programs. This allows the user to find everything that matches the specified text string and replace it. This source sample demonstrates a very bare bones version of that same functionality in Visual Basic. In general to find a sub string in a parent string you can use the InStr function which is demonstrated below. However, in order to replace the found strings with a new one you need to get a little bit trickier. See below for how this can be done in a text box.

To try out this code create a new project, add a command button to the main form, add a text box as well. Double click the command button to into the click event handler for your button. In this method add the following code.

Dim StartPos, Counter As IntegerDim FindString, ReplaceText As StringFor Counter = 1 To Len(Text1.Text)        StartPos = InStr(Text1.Text, FindString)                Text1.SelLength = Len(FindString)                Text1.SelText = "" + ReplaceText

Once you have the code in place run your application and add some text that has the string test in it. Hit the button and you will see all of these instances of the word test replaced with the string 'MyString'.

Note: The source for this was found at DreamVB which is no longer online.


View the original article here

No comments:

Post a Comment