views:

34

answers:

1

Hi all.

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.

+2  A: 

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.

ach
I'm going to try it out in a moment.
Alex Essilfie
Thanks. It works.
Alex Essilfie