Datasheet
Many times, when fetching data we simply want to display it as it is, perhaps by binding it to a grid. The
DataSet provides a local store of the data, which is often more than we need, so we can use an
OleDbDataReader to stream the data directly from the database into the grid. Let's give this a go.
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:
void Page_Load(Object sender, EventArgs e) {
DataGrid1.DataSource = GetProductsReader();
DataGrid1.DataBind();
}
10. Save the page and run it.
You'll see a grid containing just the selected columns. This doesn't look very different from the other
examples, but it's how the data is fetched that's important. Let's look at this.
How It Works
Let's start by looking at the code that the wizard generated for us. The declaration of the function returns
an
IDataReader – the interface that data readers implement:
System.Data.IDataReader GetProductsReader() {
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):
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Ole DB Services=-4; Data Source=C:\\BegASPNET11\\" +
"data\\Northwind.mdb";
System.Data.IDbConnection dbConnection =
new System.Data.OleDb.OleDbConnection(connectionString);
Next, we have the query string and the command details:
string queryString = "SELECT [Products].[ProductName], " +
"[Products].[QuantityPerUnit], [Products].[UnitPrice], " +
279
Reading from Databases
57084_08.qxp 30/01/2004 8:03 PM Page 279