Build Your Own ASP.NET 3.5 Website Using C# & VB (67 page)

Read Build Your Own ASP.NET 3.5 Website Using C# & VB Online

Authors: Cristian Darie,Zak Ruvalcaba,Wyatt Barnett

Tags: #C♯ (Computer program language), #Active server pages, #Programming Languages, #C#, #Web Page Design, #Computers, #Web site development, #internet programming, #General, #C? (Computer program language), #Internet, #Visual BASIC, #Microsoft Visual BASIC, #Application Development, #Microsoft .NET Framework

BOOK: Build Your Own ASP.NET 3.5 Website Using C# & VB
3.45Mb size Format: txt, pdf, ePub

block like so:

Visual Basic

myRepeater.DataSource = reader

myRepeater.DataBind()

Yes, it’s that easy! In a moment, we’ll display the code within the framework of a

new example. But first, let’s discuss what’s happening here in more detail.

True to its name, the Repeater control lets us output some markup for each record

in an SqlDataReader, inserting values from those records wherever we like in this

Licensed to [email protected]

372

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

repeated markup. The markup that’s to be repeated is provided as
templates
for the

Repeater to use. For example, if we wanted to display the results of a database

query in an HTML table, we could use a Repeater to generate an HTML table row

for each record in that results set. We’d provide a template containing and

tags, as well as and tags, and we’d indicate where in that template we wanted the values from the results set to appear.

To gain greater flexibility in the presentation of our results, we can provide the

Repeater control with a number of different types of templates, which the Repeater

will use in the circumstances described in the list of templates below. Each of these

templates must be specified in a child tag of the tag:


This template provides a header for the output. If we’re generating an HTML

table, for example, we could include the opening

tag, provide a row

of header cells (th), and even specify a caption for the table.


The only template that is actually required, specifies the markup

that should be output for each item in the data source. If we were generating an

HTML table, this template would contain the

tags and their

contents.


This template, if provided, will be applied instead of ItemTemplate to every

second record in the data source, making it easy to produce effects such as alternating table row colors.


This template provides markup that will appear between the items in the data

source. It will not appear before the first item or after the last item.


This template provides a footer for the control’s output, which will appear after

all the items in the data source. If you’re generating an HTML table, you could

include the closing

and
tag in this template.

Let’s take a look at a repeater control that displays a table of employees. If you want

to test this code, create a new web form named
UsingRepeater.aspx
in the Learning

Licensed to [email protected]

ADO.NET

373

application. Don’t use a code-behind file or a master page. Import the System.Data.SqlClient namespace just as you did for the two forms we created earlier in this chapter.

The following code will set up a Repeater that can be used to display a table of

employees, listing their employee IDs, names, usernames, and passwords:

LearningASP\VB\UsingRepeater.aspx
(excerpt)

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Data.SqlClient" %>

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




<br/><b>Using the Repeater<br/></b>
























Licensed to [email protected]

374

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Employee IDNameUsernamePassword
<%# Eval("EmployeeID") %><%# Eval("Name") %><%# Eval("Username") %><%# Eval("Password") %>







The Repeater control naturally lends itself to generating HTML tables, and that’s

just what we’re doing here. First, we include a , which includes

the opening

tag, along with the table’s heading row.

Next, we provide a template for each item in the result set. The template specifies

a table row containing four table cells, each of which contains a code render block

that outputs the values taken from each record in the results set. In both VB and

C#, we use Eval to retrieve database values. Alternatively, you could use the longer

form, Container.DataItem("
FieldName
") in VB.NET or DataBinder.Eval(Container.DataItem, "
FieldName
") in C#, but we’ll stick with Eval in this book. Finally, here’s the that includes the closing

tag. To

make the repeater display information, we need to bind a data source to it. Use

Visual Web Developer to generate the web form’s Page_Load event handler, and

complete it like this:

Visual Basic

LearningASP\VB\UsingRepeater.aspx
(excerpt)

Protected Sub Page_Load(ByVal sender As Object,

➥ ByVal e As System.EventArgs)

Dim conn As SqlConnection

Dim comm As SqlCommand

Dim reader As SqlDataReader

conn = New SqlConnection("Server=localhost\SqlExpress;" & _

"Database=Dorknozzle;Integrated Security=True")

comm = New SqlCommand( _

"SELECT EmployeeID, Name, Username, Password " & _

"FROM Employees", conn)

Try

conn.Open()

reader = comm.ExecuteReader()

myRepeater.DataSource = reader

myRepeater.DataBind()

Licensed to [email protected]

ADO.NET

375

reader.Close()

Catch

Response.Write("Error retrieving user data.")

Finally

conn.Close()

End Try

End Sub

C#

LearningASP\CS\UsingRepeater.aspx
(excerpt)

protected void Page_Load(object sender, EventArgs e)

{

SqlConnection conn;

SqlCommand comm;

SqlDataReader reader;

conn = new SqlConnection("Server=localhost\\SqlExpress;" +

"Database=Dorknozzle;Integrated Security=True");

comm = new SqlCommand(

"SELECT EmployeeID, Name, Username, Password " +

"FROM Employees", conn);

try

{

conn.Open();

reader = comm.ExecuteReader();

myRepeater.DataSource = reader;

myRepeater.DataBind();

reader.Close();

}

catch

{

Response.Write("Error retrieving user data.");

}

finally

{

conn.Close();

}

}

Licensed to [email protected]

376

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Figure 9.8. Using the Repeater control

As you can see, binding a control to a data source makes it very easy to get our data

to display in the web form. In this case, we’ve used the Repeater control, which,

in the server-side code, we bound to the SqlDataReader that contains our data. The

results of this work are shown in Figure 9.8
.

Creating the Dorknozzle Employee Directory

Great work! You’re presenting data in the browser window based on user interaction,

and you’ve even allowed your users to filter that data in accordance with their own

search parameters. Your code also takes care to close the database connection in

case an error occurs along the way.

It’s time to apply the theory we’re learning directly to the Dorknozzle application.

In the following pages, you’ll insert, update, and delete database records in a new

Dorknozzle Employee Directory web form. You’ll also learn how to call stored

procedures using ADO.NET.

Start by loading the Dorknozzle project and creating a new web form. Make sure

you name it
EmployeeDirectory.aspx
, check that both the
Place code in separate file
and the
Select master page
checkboxes are checked, and confirm that your new page is

based on the master page
Dorknozzle.master
. Then, modify the automatically generated

code like this:

Licensed to [email protected]

ADO.NET

377

Dorknozzle\VB\01_EmployeeDirectory.aspx
(excerpt)

<%@ Page Language="VB" MasterPageFile="~/Dorknozzle.master"

AutoEventWireup="true" CodeFile="EmployeeDirectory.aspx.vb"

Inherits="EmployeeDirectory"

title="
Dorknozzle Employee Directory
" %>

Runat="Server">


ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

Employee Directory



Employee ID:

<%#Eval("EmployeeID")%>

Name: <%#Eval("Name")%>

Username: <%#Eval("Username")%>








This Repeater includes item and separator templates. The item template contains

code render blocks that will display the data from an SqlDataReader. When this

repeater is properly populated with data, the employee directory page will look like

the one shown in Figure 9.9
.

Licensed to [email protected]

378

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Figure 9.9. The completed Employee Directory page

First up, let’s write the code that populates the repeater control. That code will take

the form of a Page_Load method within our code-behind file. To have the method’s

signature generated for you, switch the form to Design view, and double-click an

empty space on the form (not in the space of other controls such as the Repeater;

a good place to double-click would be to the right of the Employee Directory header).

Then, add this code:

Visual Basic

Dorknozzle\VB\02_EmployeeDirectory.aspx.vb
(excerpt)

Imports System.Data.SqlClient

Imports System.Configuration

Partial Class EmployeeDirectory

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object,

➥ ByVal e As System.EventArgs) Handles Me.Load

Dim conn As SqlConnection

Dim comm As SqlCommand

Dim reader As SqlDataReader

Dim connectionString As String = _

Other books

The Resort by Bentley Little
Death in a Major by Sarah Fox
The Trowie Mound Murders by Marsali Taylor
The Wall of Winnipeg and Me by Mariana Zapata