Interacting with Databases Using ASP.NET 2.0 with the Microsoft Data Access Application Block - Retrieving a single row in the form of a data row using the Data Access Application Block
(Page 3 of 6 )
In previous sections, we worked with datasets and data tables. In this section, we shall retrieve a single row in the form of a data row, by passing a SELECT statement to the Data Access Application Block.
The following is the complete code needed to retrieve a data row by passing a SELECT statement to the Data Access Application Block.
ImportsSystem.Data
ImportsMicrosoft.Practices.EnterpriseLibrary.Data.Sql
ImportsMicrosoft.Practices.EnterpriseLibrary.Data
PartialClass _Default
Inherits System.Web.UI.Page
Protected Sub btnConnect_Click(ByVal sender As Object, ByVal
e As System.EventArgs) Handles btnConnect.Click
Dim dr As DataRow = getDataRow("select * from
HumanResources.department where departmentid=2")
Me.lblMsg.Text = dr("Name") & ", " & dr("GroupName")
End Sub
Private Function getDataRow(ByVal SQl As String) As DataRow
Dim db As SqlDatabase = DirectCast
(DatabaseFactory.CreateDatabase("AdventureWorks"), SqlDatabase)
Dim dt As DataTable = db.ExecuteDataSet(CommandType.Text,
SQl).Tables(0)
Dim dr As DataRow = dt.Rows(0)
Return dr
End Function
EndClass
You can observe that in the above code, I defined my own function, “getDataRow,” which accepts a SELECT statement as a parameter and returns a “Datarow” object. This lets us reuse the function any number of times within the same form very easily.
Let me explain it a bit. First, I retrieve a data table using the following code:
Dim dt As DataTable = db.ExecuteDataSet(CommandType.Text,
"select * from HumanResources.department").Tables(0)
Once the data table is filled, we can select only the first row in that table and return to the calling method using the following:
Dim dr As DataRow = dt.Rows(0)
Return dr
Next: Retrieving a single value using the Data Access Application Block >>
More ASP.NET Articles
More By Jagadish Chaterjee