fedeteka fedeteka - 11 days ago 5
Vb.net Question

DatagridView: how to programmatically move the current index to the programmatically selected row?

On a textfield the user can type a name then press a button and the program search the name on the DataGridView and highlight the row of the record

The search and highlight loop

For Each row In DataGrid.Rows
If row.Cells("userName").Value = userNameToSearch Then
row.Selected = True
Exit For
End If
Next


The loops works fine

Then I need to move the index of the DataGridView to match that row

If I use

Dim MyFindedIndex As Integer
MyFindedIndex = DataGrid.CurrentRow.Index


I get a 0 even if I know the matched and highlighted row is number 7 by example.

If I understand well I also need to move the index of the current cell because is the current cell the one who determine the value of the index

I can do that forcing to move to the index number 7

DataGrid.CurrentCell = DataGrid.Item(0, 7)


But I need to do that programmatically (find the "7" number)

Maybe using IndexOf or something like that?




Solution

Using Fabio answer!

The column of the cell needs to be visible, and that was not the case on my DataGridView because the cell contains a primary key number the user didn't need to see

The solution: one cell for the search, one cell for the position (this one visible)

For Each row In DataGrid.Rows
'Cell to search
Dim cell As DataGridViewCell = row.Cells("userNumber")
'Cell to position
Dim cell2 As DataGridViewCell = row.Cells("userName")
If cell.Value.ToString().Equals(userNumberToSearch) = True Then
DataGrid.CurrentCell = cell2
Exit For
End If
Next


If the column of the cell was not visible VB Throw System Null Reference

Answer

It is enough to set DataGridView.CurrentCell. Do it in your search loop

For Each row In DataGrid.Rows
    Dim cell As DataGridViewCell = row.Cells("userName")
    If cell.Value.ToString().Equals(userNameToSearch) = True Then                
        DataGrid.CurrentCell = cell
        Exit For
    End If
Next
Comments