Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

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" %>

  <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;" + _
     Dim cmd as New SqlCommand("SELECT * FROM Employees", conn)

     Dim reader as SqlDataReader

     reader = cmd.ExecuteReader()

     employees.DataSource = reader


   End Sub


<h1>Creating a DataReader</h1>

<form runat="server" id=form1 name=form1>
  <asp:DataGrid id="employees" runat="server"></asp:DataGrid>



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.

  • + Share This
  • 🔖 Save To Your Account