How to Search/Find Text in a Textbox control in VB.NET, VB 2008, 2010, and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.50 out of 5)
 

Most any kind of word processing application from the basic Windows Notepad to the more advanced OpenOffice Writer includes a feature to search its text. There are other reasons to implement a textbox search feature and hopefuly this article will show you how. The normal textbox control in .NET does not have any find/search capabilities that I could find. So I ended up having to create my own searching code for a control I made along time ago and thought it could be useful for someone if I posted it.

Visual Basic.NET, VB 2008/2010/2013

Since DotNET doesn’t have built-in support for searching/finding text, you will need to make your own code. This is a snippet I originally made for a more advanced textbox control called: ‘csTextBoxX’. There are many other features available as well if you want to take a look at it here and with an example here.


Below is the Function I made…

'
'I’m sure this Function can be more refined if you wanted to do it.
'
Public Overloads Function SearchText(ByVal textToFind As String, Optional ByVal startPosition As Integer = 0, Optional ByVal endPosition As Integer = 0, Optional ByVal highlightText As Boolean = True, Optional ByVal matchCase As Boolean = False) As Integer
'
'Contains the return value of the search. IT it returns -1, then a match was not found.
Dim i As Integer

If endPosition < 1 Then

  If Not matchCase Then

    textToFind = textToFind.ToLower

  Dim temp As String = Textbox.Text.ToLower

    i = temp.IndexOf(textToFind, startPosition, Me.Text.Length)

  Else

    i = Textbox.Text.IndexOf(textToFind, startPosition, Me.Text.Length)

  End If

Else

  If matchCase = False Then

      textToFind = textToFind.ToLower

      Dim temp As String = Textbox.Text.ToLower

      i = temp.IndexOf(textToFind, startPosition, endPosition)

  Else

      i = Textbox.Text.IndexOf(textToFind, startPosition, endPosition)

  End If

End If

If i > -1 Then

  If highlightText Then

    Textbox.Focus()

    Textbox.SelectionStart = i

    Textbox.SelectionLength = textToFind.Length

  End If

End If
'
'Returns the position the text was found at, otherwise it will report -1, which means that the search string was not found.
  Return i

End Function

Unfortunately my Function may not be easy to understand but It does work. You can also go through it and refine/optimize it where you can. I’m sure there are areas that need some attention.

The function supports Match Casing, No Match Casing, and Search at a specific Starting and/or Ending position within the text. There is also an option whether to Highlight the text that was found or not. Check out the example below to see it in use…

'
'Will contain the position where the text was found.
  Dim textFound As Integer
'
'Find the first occurance of the text “box” at the beginning of the textbox through to the end of the textbox. Selected True to Highlight the text that was found and disabled searching text for the same casing.
  textFound = SearchText(“box”, 0, Textbox.TextLength, True, False)
'
'Display a message with the starting position of the text if it was found. If a -1 is returned then it means it did Not find the specified text.
  MsgBox(textFound.ToString)

The example above starts searching at the beginning of the text and will go to the end of the text to find a match. It was set to highlight the text if found and not to worry about matching the text casing.


That’s all I guess. As a side note, I was almost sure that Visual Basic 2005 (.NET 2.0 and Newer) added a find/search feature in the textbox control but I couldn’t find it. So you can use this function for VB 2005, Visual Basic 2008, VB 2010, and newer. Have fun 🙂

Jason

Revised: 2014

9 thoughts on “How to Search/Find Text in a Textbox control in VB.NET, VB 2008, 2010, and Higher

  1. May,Thailand
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            Dim path As String = "IT1845?"
    
            Dim text As String
            Dim name As String
            Dim newLineindex As Integer
            Dim nameIndex As Integer
    
            ListBox.Items.Clear()
    
            If My.Computer.FileSystem.FileExists(path & "phonelist.txt") Then
                text = My.Computer.FileSystem.ReadAllText(path & "phonelist.txt")
                newLineindex = text.IndexOf(ControlChars.NewLine, nameIndex)
                Do Until newLineindex = -1
                    name = text.Substring(nameIndex, newLineindex – nameIndex)
                    ListBox.Items.Add(name)
    
                    nameIndex = newLineindex + 2
                    newLineindex = text.IndexOf(ControlChars.NewLine, nameIndex)
                Loop
            End If
    
        End Sub
    
    Reply
  2. Arindam Ghosh

    No friends I can’t Tell It Very Very Good…..
    I can Give You a Better Class.Just Create Object Of This class And Find Your Selected text Without using any textbox.
    Use this code in click event of a button or a contextmenu.I have used Context menu.If You use any Shortkut like Ctrl+F then it will react like Ms word’s Find Function.
    My class…………………………………..

    Public Class clsfindreplace
        Public i As Integer = 1
        Public status As Integer = 0
        Public Function find_text(ByRef textbox As TextBox)
    
            Dim Where As String
            ' Get search string from user.
            ' Find string in text.
            Where = InStr(i, textbox.Text.ToLower, textbox.SelectedText.ToLower)
            'MessageBox.Show(Where)
    
            If Where Then
                textbox.Focus()
                textbox.SelectionStart = Where – 1
                textbox.SelectionLength = Len(textbox.SelectedText)
                i = Val(Where) + Len(textbox.SelectedText)
                status = status + 1
            Else
                If status = 0 Then
                    MsgBox("Searching Is Complited………")
                Else
                    MsgBox("String not found.")
                End If
                i = 1
                status = 0
            End If
    
            Return textbox
    
        End Function
    End Class
    
    'Now the event in which i have applied the function:————————————
    Private Sub FindToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindToolStripMenuItem.Click
        If txtContent.SelectedText = "" Then
            MessageBox.Show("No content is selected…", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Sub
        End If
        find.find_text(txtContent)
    End Sub
    

    Take Care


    Use it ……….

    Reply
  3. punit

    hi, i m using 2 texbox but unable to search the word from textbox1 to textbox2 & highlighting it in textbox2 bcoz text is present in it . Highlighted text color should be changed.

    send me vb code of asp.net
    thanks
    in advance
    plz mail me

    Reply
  4. wonderFul

    hi nice work but you cant select or highted next word if there is two same word, it just select the first word then it stay there forever. Is there possible if it founds multi same word each time you click the search button goes to next word! please do that if you can THANKS ONCE AGAIN

    Reply
  5. hey

    hey i’m in year 10 and I have been given a task the task is to write a program that works out a sentence that holds numerous words without any punctuation. When a word in that sentence is input the program analyses the location where the word is in that sentence. The system should NOT be case sensitive please help

    Reply

Leave a Reply

Your email address will not be published.