Datasheet
Try It Out Using a DataReader
1.
Create a new blank ASP.NET page called DataReader.aspx.
2. Drag a DataGrid control from the Toolbox onto the page.
3. Switch to Code view and start the code wizard by dragging the SELECT Data Method onto the
code page.
4. Select the existing database connection from the first screen and press Next.
5. Select the Products table, and from the Columns select ProductName, QuantityPerUnit, UnitPrice,
and
UnitsInStock.
6. Click Next, and Next again, to go past the Query Preview screen.
7. Enter GetProductsReader as the method name, and select the DataReader option on the Name
Method
screen.
8. Press Finish to insert the code into your page.
9. Underneath the newly inserted method, add the following:
Sub Page_Load(Sender As Object, E As EventArgs)
DataGrid1.DataSource = GetProductsReader()
DataGrid1.DataBind()
End Sub
10. Save the page and run it.
You'll see a grid containing just the selected columns. This isn't much different in look from other
examples, but it's how the data is fetched that's important. Let's take a look at this.
How It Works
Let's start by looking at the code the wizard generated for us. The declaration of the function returns an
IDataReader – the interface that data readers implement:
Function GetProductsReader() As System.Data.IDataReader
Next we have the connection details – these are the same as you've previously seen (although they might
look different in your code file, as this has been formatted to fit on the page):
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Ole DB Services=-4; " & _
"Data Source=C:\BegASPNET11\data\Northwind.mdb"
Dim dbConnection As System.Data.IDbConnection = _
New System.Data.OleDb.OleDbConnection(connectionString)
Next we have the query string and the command details:
Dim queryString As String = "SELECT [Products].[ProductName], " & _
"[Products].[QuantityPerUnit], [Products].[UnitPrice], " &
_
"[Products].[UnitsInStock] FROM [Products]"
284
Chapter 8
57076_Ch 8 SAN.qxd 01/12/2003 6:43 PM Page 284