Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

5. Windows Forms Datagrid

5.78 How do I retrieve the current row from a DataTable bound to a DataGrid 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.

[C#]
     DataTable dt = (DataTable) this.dataGrid1.DataSource;
     DataRow dr = dt.Rows[this.dataGrid1.CurrentRowIndex);
[VB.NET]
     Dim dt As DataTable = Me.DataGrid1.DataSource
     Dim dr as DataRow = dt.Rows(Me.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.

[C#]
     BindingManagerBase bm = this.dataGrid1.BindingContextr[this.dataGrid1.DataSource, this.dataGrid1.DataMember];
     DataRow dr = ((DataRowView)bm.Current).Row;
[VB.NET]
     Dim bm As BindingManagerBase = Me.DataGrid1.BindingContext(Me.DataGrid1.DataSource, Me.DataGrid1.DataMember)
     Dim dr As DataRow = CType(bm.Current, DataRowView).Row