Reputation: 12613
When I use a DataTable
as a DataGridView
's DataSource
, I often have to find which row(s) a user has selected and read specific values from the DataTable (not the DataGridView)
I wanted to know if there is any reliable way of determining which DataRow
a DataGridViewRow
is bound to especially when the user has sorted the DataGridView on a column other than the default order.
Currently, I use code of this sort:
Dim sorting = ""
If DataGrid.SortOrder <> SortOrder.None Then
'get the actual row if the results are sorted'
sorting = "[" & DataGrid.SortedColumn.Name & "]" &
If(DataGrid.SortOrder = SortOrder.Ascending, "", " DESC")
End If
'return the selected row after sorting'
Dim selectedRowIndices = (From r In DataGrid.SelectedRows Select
DirectCast(r, DataGridViewRow).Index).ToArray
SelectedDataRow = (DataTable.Select("", sorting).Where(
Function(r As DataRow, i As Integer) i = selectedRowIndex)
).FirstOrDefault
Thanks.
Upvotes: 1
Views: 2222
Reputation: 7421
DataGridViewRow.DataBoundItem will give you a dataViewRow for the current item in the Databound dataTable (dataview).
So:
Dim drv as DataRowView = myDataGridViewRow.DataBoundItem
Dim dr as DataRow = drv.Row
Will give you the DataRow from your datagridviewrow.
Upvotes: 4