08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

88<br />

CHAPTER 4 ■ DATA BINDING WITH <strong>ASP</strong>.<strong>NET</strong><br />

In the next section, you’ll see how to use this reader to step through the results of the<br />

query <strong>and</strong> access the first line of the returned addresses.<br />

Reading the Data<br />

When you execute the previous comm<strong>and</strong>, ADO.<strong>NET</strong> returns a SqlDataReader. This reader<br />

is a forward-based read-only cursor that moves forward by one record every time you call<br />

its Read method. The Read method returns True if it reads a record <strong>and</strong> False otherwise.<br />

Upon a successful read, it will then load an array of values with the index of the array representing<br />

the column name—so reader["ColumnName"] will contain this record’s value for<br />

ColumnName.<br />

Thus, we can iterate through the returned result set using a while loop, <strong>and</strong> upon a<br />

successful read, retrieve the result set’s data by simply accessing the reader as if it were an<br />

array.<br />

Listing 4-1 contains the complete code to access the addresses for postal code 98011<br />

in the AdventureWorks database.<br />

Listing 4-1. Using Connection, Comm<strong>and</strong>, <strong>and</strong> Reader to Access Data<br />

using System;<br />

using System.Data;<br />

using System.Configuration;<br />

using System.<strong>Web</strong>;<br />

using System.<strong>Web</strong>.Security;<br />

using System.<strong>Web</strong>.UI;<br />

using System.<strong>Web</strong>.UI.<strong>Web</strong>Controls;<br />

using System.<strong>Web</strong>.UI.<strong>Web</strong>Controls.<strong>Web</strong>Parts;<br />

using System.<strong>Web</strong>.UI.HtmlControls;<br />

using System.<strong>Web</strong>.Configuration;<br />

using System.Data.SqlClient;<br />

using System.Text;<br />

public partial class _Default : System.<strong>Web</strong>.UI.Page<br />

{<br />

protected void Page_Load(object sender, EventArgs e)<br />

{<br />

string connectionString =<br />

<strong>Web</strong>ConfigurationManager.ConnectionStrings["AW"].ConnectionString;<br />

StringBuilder strReturn = new StringBuilder();<br />

using (SqlConnection sqlCon = new SqlConnection(connectionString))<br />

{<br />

SqlComm<strong>and</strong> sqlComm = new SqlComm<strong>and</strong>();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!