How to Find Row Index by PrimaryKey of DataTable

  • Thread starter Thread starter Ivan
  • Start date Start date
I

Ivan

Dear All,

Does Anyone know how to retrieve the row index if i already know the
primarykey of a datatable??

Thanks All,

Ivan
 
¤ Thanks Paul... I just forgot about this simple method....
¤ cheers,
¤ Ivan

Actually after reading your message again there is a solution that might be a little closer to what
you are looking for. There is a Find method for the DataRowCollection. The below example uses Access
but it should be applicable to other database types:

Dim ConnectionString As String

ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=e:\My Documents\db1.mdb"
Dim AccessConnection As New System.Data.OleDb.OleDbConnection(ConnectionString)
AccessConnection.Open()

Dim da As New System.Data.OleDb.OleDbDataAdapter("Select * from Table2", AccessConnection)
Dim dt As New DataTable()
da.Fill(dt)

dt.PrimaryKey = New DataColumn() {dt.Columns("record ID")}
Dim dr As DataRow = dt.Rows.Find(4) '4 is the value of the key field
If dr Is Nothing Then
Console.WriteLine("Not found")
Else
Console.WriteLine(dr("record id"))
End If

AccessConnection.Close()


Paul ~~~ (e-mail address removed)
Microsoft MVP (Visual Basic)
 
Back
Top