Get the current row from a DataSet after sorting its bound DataGrid

This is a common dilemma in WinForms applications. You display a DataGrid that's bound to an underlying DataSet or DataTable. The user clicks the DataGrid's headrow and sorts the data after they have added and deleted several rows.

In an unsorted grid you can use the following to get the current row:

    Dim dt As DataTable = DataGrid.DataSource 
    Dim dr as DataRow = dt.Rows(DataGrid.CurrentRowIndex)

If the grid has been sorted, you can no longer get the current row using the grid's CurrentRowIndex property. However, for both unsorted and sorted grids, you can get the current row through the BindingContext and the Current property of the BindingManagerBase.

    Dim bm As BindingManagerBase = DataGrid.BindingContext( _
            DataGrid.DataSource, DataGrid.DataMember)
    Dim dr As DataRow = CType(bm.Current, DataRowView).Row 

You can also use the CurrencyManager which maps a DataGrid row to the corresponding DataSet row.

    ' Specify the CurrencyManager
    Dim cm As CurrencyManager = _
        CType(DataGrid.BindingContext(DataGrid.DataSource), CurrencyManager)
    Dim dr As DataRow

    ' Display the current row number, get the current row and
    ' display the first column's value.
    dr = myDataSet.Tables(0).Rows(cm.Position)

About TheScarms
About TheScarms

Sample code
version info

If you use this code, please mention ""

Email this page

© Copyright 2016 TheScarms
Goto top of page