Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

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;

Contributed from George Shepherd's Windows Forms FAQ



Page view counter