Search Amazon:

How to 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)
    Debug.WriteLine(cm.Position)
    Debug.WriteLine(dr(0))
Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Be the first to add a comment! Items to Show:     

     
You must log in to post feedback.
Comment:    
 

If you use this code, please mention "www.TheScarms.com"

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms