Instantiating the DataReader
The DataReader is very easy to use. To get an instance of the DataReader object, you call the ExecuteReader() of the Command object, rather than using the DataAdapter. The ExecuteReader() returns a new instance of a DataReader object ready to display data starting at the first record returned. The code in Listing 8.2 (VB .NET) and in Listing 8.3 (C#) shows how to get a DataReader object.
Listing 8.2 Getting an Instance of the DataReader in Visual Basic .NET
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()
Listing 8.3 Getting an Instance of the DataReader in C#
SqlConnection conn = new SqlConnection("Initial Catalog=Northwind;" + "Server=(local);UID=sa;PWD=;"); SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn); SqlDataReader reader; conn.Open(); reader = cmd.ExecuteReader();
In Listings 8.2 and 8.3, line 1 instantiates a new connection object. Line 3 creates a new object of type SqlDataReader. The connection is then opened and a new SqlDataReader object is created using the ExecuteReader() method.
This is significantly easier than retrieving a DataSet! Now that you know how to get a DataReader, it's time to see what the DataReader can do. In the next few sections, you'll see how to use the DataReader to step through database records and bind to Web controls.