ServerName, InstanceName, DatabaseName, Username, and Password with the
appropriate details for your server.
Visual Basic File: AccessingData.aspx (excerpt)
' Define database connection
Dim conn As New SqlConnection(
"Server=ServerName\InstanceName;" & _
"Database=DatabaseName;User ID=Username;" & _
"Password=Password")
C# File: AccessingData.aspx (excerpt)
// Define database connection
SqlConnection conn = new SqlConnection(
"Server=ServerName\\InstanceName;" +
"Database=DatabaseName;User ID=Username;" +
"Password=Password");
Reading the Data
Okay, so youve opened the connection and executed the command. Lets do
something with the returned data!
A good task for us to start with is to display the list of employees we read from
the database. To do this, well simply use a While loop to add the data to a Label
control that well place in the form. Start by adding a Label named employeesLa-
bel to the AccessingData.aspx web form. Well also change the title of the page
to Using ADO.NET.
File: AccessingData.aspx (excerpt)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Using ADO.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="employeesLabel" runat="server" />
</div>
</form>
</body>
</html>
342
Chapter 9: ADO.NET
Now, lets use the SqlDataReaders Read method to loop through the data items
held in the reader; well display them by adding their text to the employeesLabel
object as we go.
Visual Basic File: AccessingData.aspx (excerpt)
' Open connection
conn.Open()
' Execute the command
Dim reader As SqlDataReader = comm.ExecuteReader()
' Read and display the data
While reader.Read()
employeesLabel.Text &= reader.Item("Name") & "<br />"
End While
' Close the reader and the connection
reader.Close()
conn.Close()
C# File: AccessingData.aspx (excerpt)
// Open connection
conn.Open();
// Execute the command
SqlDataReader reader = comm.ExecuteReader();
// Read and display the data
while(reader.Read())
{
employeesLabel.Text += reader["Name"] + "<br />";
}
// Close the reader and the connection
reader.Close();
conn.Close();
Figure 9.4. Displaying the list of employees
343
Reading the Data

Get Build Your Own ASP.NET 2.0 Web Site Using C# & VB, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.