Searching DataGridView and Selecting Match

How would I search a DataGridView's first column for a Value and select the row IF the Value is there? -- Much like a WHERE Clause in SQL.

I've been looking around for an answer in threads but I can't seem to find one.

DataGridView1 is the DataGridView and My.Settings.CurrentUserID is the Value I want to search for.

Any help would be appreciated.

Note; There can only be one occurrence of the Value in the table, so there is no concern for multiple returns/matches.

{Edit 1}

Steves solution seems to only highlight the row and not actually select it as the Black arrow doesn't move onto it. The value the code's looking for is 4, notice how it finds it and highlights it, but the arrow doesn't move.

The code does this:

I need it to do this:

Answers


Well supposing that the column you want to search is the first one then

For Each row in DataGridView1.Rows
    If Convert.ToInt32(row.Cells(0).Value) = My.Settings.CurrentUserID Then
        row.Selected = True
        Exit For
    End If
Next

EDIT:

To indicate the "current" row, set the CurrentCell property of the datagridview.

   .....
   DataGridView1.CurrentCell = row.Cells(0)
   Exit For

From MSDN:

When you set a cell as the current cell, it will scroll into view if it is not currently displayed. The current cell cannot be a header cell, a disabled cell, or a cell in a hidden row or column.


Put this in a click event or whatever...

    Dim intIndex As Integer = FindUser(txtSearchString.Text, txtColumn.Text)
    dgvMembers.CurrentCell = dgvMembers.Rows(intIndex).Cells(0) 'This ensures that the    arrow will move

Put this in your class or wherever...

  Private Function FindUser(ByVal strUserID As String, ByVal intColumn As Integer) As Integer
    Dim intIndex As Integer = 0

    For i As Integer = 0 To dgvMembers.Rows.Count - 1
        If dgvMembers.Rows(i).Cells(intColumn).Value.ToString = strUserID Then
            intIndex = i
            Exit For
        End If
    Next

    Return intIndex
End Function

Need Your Help

How to create a button and locate it on a panel based on user input

java eclipse jbutton form-layout

In first frame, I have a panel with form layout, I have a "ADD" button. When user click ADD button, a second frame will shown. Second frame is shown to allow user to fill the information needed to ...