Binding DataReader Results to a Web Control
The most common use for the DataReader is to bind it to Web controls, much in the same way as you'd bind a DataSet. Other than the fact that you've eliminated overhead by not creating a DataSet, binding to a DataReader is almost exactly the same as binding to a DataSet. The code in Listing 8.4 demonstrates how to bind the DataReader. When run, this Web form will appear identical to the one in Figure 8.1. Notice that in line 22, the DataReader object is passed directly to the DataSource of the DataGrid Web control.
Listing 8.4 Data Binding the DataReader Object to a Web Control
<% @Page Language="VB" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <HTML> <HEAD> <LINK rel="stylesheet" type="text/css" href="Main.css"> <!-- End Style Sheet --> <script language="VB" runat="server" > Sub Page_Load(Source as Object, E as EventArgs) Dim conn as New SqlConnection("Initial Catalog=Northwind;" + _ "Server=(local);UID=sa;PWD=;") Dim cmd as New SqlCommand("SELECT * FROM Employees", conn) Dim reader as SqlDataReader conn.Open() reader = cmd.ExecuteReader() employees.DataSource = reader employees.DataBind() conn.Close() End Sub </script> </HEAD> <BODY> <h1>Creating a DataReader</h1> <hr> <form runat="server" id=form1 name=form1> <asp:DataGrid id="employees" runat="server"></asp:DataGrid> </form> <hr> </BODY> </HTML>
Just as with the DataAdapter method of retrieving data, you should close your connection to the database as soon as you can. Because the DataReader requires an active connection to the database while it is data binding, you should close the connection to the database just after the data-binding statements. In addition, when you are done reading records from the DataReader, you should call the Close() method of the DataReader to save system resources.
Because the DataReader supports the IEnumerable interface, it can be bound directly to the DataSource property of a Web control or any other control that supports data binding.