Monday, April 16, 2007

VS2003: How do I retrieve the current row from a DataTable to which a DataGrid is bound after the grid has been sorted?


In an unsorted DataGrid bound to a DataTable, you can get a reference to a row in the DataTable through the DataGrid.CurrentRowIndex. DataTable dataTable = (DataTable)

dataGrid1.DataSource;
DataRow dataRow = dataTable.Rows[ dataGrid1.CurrentRowIndex ];

But if the grid has been sorted, you can no longer get at the current row in the table through the grid's CurrentRowIndex. But for both unsorted and sorted grids, you can get at the current row through the BindingContext and the Current property of the BindingManagerBase.

BindingManagerBase bm =
dataGrid1.BindingContextr[ dataGrid1.DataSource, dataGrid1.DataMember ];
DataRow dataRow = ( (DataRowView) bm.Current ).Row;