Live Chat Icon For mobile
Live Chat Icon

How do I retrieve the current row from a DataTable bound to a DataGrid after the grid has been sorted

Platform: WinForms| Category: Datagrid

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

	DataTable dt = (DataTable) this.dataGrid1.DataSource;
	DataRow dr = dt.Rows[this.dataGrid1.CurrentRowIndex);
	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.

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

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.