Returning the selected datagrid row from the underlying data table

  • Thread starter Thread starter Brian Mitchell
  • Start date Start date
B

Brian Mitchell

Ok, I know this is an elementary question but I have a data grid that is
bound to a data table and I can't seem to find a way to match the selected
row in the grid with it's respective row in the underlying data table.

If the rows in the grid are in the same order as the rows in the table then
I can use the Datagrid.CurrentRowIndex to return the same row from the data
table. But if the user sorts the data in the grid then the row order in the
grid no longer match the row order in the data table.

My question is: How do I return a reference to the row in the underlying
data source from the data grid?

Thanks!!
 
Hi,

Quick example. Needs a windows form with a datagrid and button.

Public WithEvents ds As New DataSet

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim strConn As String
Dim conn As OleDbConnection
Dim da As OleDbDataAdapter

strConn = "Provider = Microsoft.Jet.OLEDB.4.0;"
strConn &= "Data Source = Northwind.mdb;"


conn = New OleDbConnection(strConn)
da = New OleDbDataAdapter("Select * From Categories", conn)
da.Fill(ds, "Categories")
DataGrid1.DataSource = ds.Tables("Categories")

End Sub

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim cmCurrent As CurrencyManager =
CType(Me.BindingContext(DataGrid1.DataSource), CurrencyManager)

Dim dr As DataRowView =
ds.Tables(0).DefaultView.Item(cmCurrent.Position)
Debug.WriteLine(dr.Item(1))
End Sub


Ken
 
Yep, that DataRowView did it for me.

Thanks!!!


Ken Tucker said:
Hi,

Quick example. Needs a windows form with a datagrid and button.

Public WithEvents ds As New DataSet

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim strConn As String
Dim conn As OleDbConnection
Dim da As OleDbDataAdapter

strConn = "Provider = Microsoft.Jet.OLEDB.4.0;"
strConn &= "Data Source = Northwind.mdb;"


conn = New OleDbConnection(strConn)
da = New OleDbDataAdapter("Select * From Categories", conn)
da.Fill(ds, "Categories")
DataGrid1.DataSource = ds.Tables("Categories")

End Sub

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim cmCurrent As CurrencyManager =
CType(Me.BindingContext(DataGrid1.DataSource), CurrencyManager)

Dim dr As DataRowView =
ds.Tables(0).DefaultView.Item(cmCurrent.Position)
Debug.WriteLine(dr.Item(1))
End Sub


Ken
 
Back
Top