troubleshooting Question

Progressive search in DataGridView

Avatar of ElrondCT
ElrondCTFlag for United States of America asked on
Visual Basic.NET
8 Comments1 Solution1311 ViewsLast Modified:
In VB 2008, I have a DataGridView with a list of item numbers. I would like to implement a progressive search through the list, so that if the user types "L", the DataGridView immediately jumps to the first entry that starts with L. Then if the user types "I", it jumps to the first entry that starts with LI. And so on (if no match is found, the program beeps).

I've tried setting up code in the KeyPress event handler for the DataGridView using the Find method of the DataView that is the DataSource. However, Find only does an exact match, not a "begins with" match, so this only works with single-character key values--not very useful! I can't figure out how to do a "begins with" search and get the result selected in the DataGridView.

I've seen some code online that does progressive filtering of the list based on what you've typed (i.e., only the records that match are displayed). However, that's not what I'm looking for: I want the entire list displayed, but the first matching entry highlighted. (Ideally, I'd like to have the letters typed highlighted in the selected cell, but that's probably a separate topic.)
Private Sub dgvNumbers_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles dgvNumbers.KeyPress
        Dim intSearch As Integer
        Dim dgcCurrent As DataGridViewCell
        strSearch &= e.KeyChar
        intSearch = dvNumbers.Find(strSearch)
        If intSearch = -1 Then
            My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)  ' Play bell
            strSearch = Mid(strSearch, 1, Len(strSearch) - 1)           ' Delete that character from our search string
        Else
            dgGoTo.CurrentRowIndex = intSearch
            dgvNumbers.FirstDisplayedScrollingRowIndex = intSearch
            dgvNumbers.Rows(intSearch).Selected = True
            dgvNumbers.Rows(intCurIndex).Selected = False
            intCurIndex = intSearch
            dgcCurrent = dgvNumbers.CurrentCell
        End If
    End Sub
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 8 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 8 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros