I am trying to do a search on a datagridview from a string the operator enters into a textbox. I am searching the datagrid view on a sorted column of last names. I do not want to filter the datagridview. I would like the operator to be able to search for partial matches. As an example: If the operator is searching for the last name of wilson, they should be able to enter w, wi, wil, wils, wilso, or wilson into the text box and search the last name column for the first row that matches their entry. In this way if they search for "wil" they might land on a row and select it that has the last name of williams when they are actually looking for wilson. They will then be able to scroll down to the row they are looking for and select it. Sometimes the last names are misspelled and other times they operator may not be able to spell the last name.

The code I have will find the last name but only if it is a complete match. Can anyone help me with this?

    Dim Found As Boolean = False
    Dim StringToSearch As String = ""
    Dim ValueToSearchFor As String = Me.TextBox1.Text.Trim.ToLower
    Dim CurrentRowIndex As Integer = 0

        If DataGridView1.Rows.Count = 0 Then
            CurrentRowIndex = 0
            CurrentRowIndex = DataGridView1.CurrentRow.Index + 1
        End If
        If CurrentRowIndex > DataGridView1.Rows.Count Then
            CurrentRowIndex = DataGridView1.Rows.Count - 1
        End If

        If DataGridView1.Rows.Count > 0 Then
            For Each gRow As DataGridViewRow In DataGridView1.Rows
                StringToSearch = gRow.Cells(1).Value.ToString.Trim.ToLower
                If StringToSearch Like (Me.TextBox1.Text) Then
                    Dim myCurrentCell As DataGridViewCell = gRow.Cells(1)
                    Dim myCurrentPosition As DataGridViewCell = gRow.Cells(0)
                    DataGridView1.CurrentCell = myCurrentCell
                    CurrentRowIndex = DataGridView1.CurrentRow.Index
                    DataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.LightSkyBlue
                    Found = True
                End If

                If Found Then
                    Exit For
3 Years
Discussion Span
Last Post by G_Waddell

You should just in case also convert your search string to lower to ensure both the search string and the string being searched are in the same case.

Why not use Instr?

IF Instr(StringToSearch, lcase(trim(Textbox1.Text))) <> 0 Then
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.