Domanda

I am trying to select a newly added item in the DataGridView which is bound to a DataTable of items. I know we can loop through the DataGridView and find it...

Select Row (DataGridView Loop)

Private Sub SelectNewDgvItem(ByVal Item As clsItem, ByVal Dgv As DataGridView)
    For each r as DataGridViewRow In Dgv.Rows
        If r.Cells("PK_Item").Value = Item.PK_Item Then
           r.Selected()

           'Ensures visibility of the row if r.Cells("PK_Item") is visible
           Dgv.CurrentCell = r.Cells("PK_Item") 
           Exit For
        End If
    Next
End Sub

I'm trying to figure out if we can select the DataGridView row using the DataTable

È stato utile?

Soluzione

The proper way would be to bind the DataTable to a BindingSource and then bind the BindingSource to the DataGridView. You can then call the Find method of the BindingSource to get the index of a row, which may or may not match the index of the corresponding row in the original DataTable. You can then use that index to get a DataGridViewRow from the Rows collection of the grid and/or you can assign it to the Position property of the BindingSource to make that the current row in the UI. This is just one example of why you should generally use a BindingSource when binding in WinForms.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top