Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: ASP.NET
Description: Notes for ASP.NET

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Summary of Contents
Preface
...
Introducing ASP
...
NET Platform
...
ASP
...
33
3
...
51
4
...
NET Web Pages
...
Building Web Applications
...
Using the Validation Controls
...
Database Design and Development
...
Speaking SQL
...
ADO
...
331
10
...
401
11
...
427
12
...
469
13
...
527
14
...
571
A
...
611
Index
...
NET 2
...
NET 2
...
Ltd
...
No part of this book may be reproduced, stored in a retrieval system or transmitted
in any form or by any means, without the prior written permission of the publisher, except in the
case of brief quotations embodied in critical articles or reviews
...

However, the information contained in this book is sold without warranty, either express or implied
...
Ltd
...


Trademark Notice
Rather than indicating every occurrence of a trademarked name as such, this book uses the names
only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark
...
Ltd
...

Web: www
...
com
Email: business@sitepoint
...

He holds a Bachelor’s Degree from San Diego State University and a Master of Science
in Instructional Technology from National University in San Diego
...
More recently, he’s worked as a wireless software engineer
developing
...
Currently, Zak holds a programming position with ADCS Inc
...
NET applications
...
He also lectures on various
technologies and tools, including Dreamweaver and ASP
...

Cristian Darie is a software engineer with experience in a wide range of modern technologies, and the author of numerous technical books, including the popular Beginning ECommerce series
...
From there, Cristian moved on to many other similar achievements, and is
now studying distributed application architectures for his PhD
...
Cristian can be contacted through his personal
web site at http://www
...
ro
...
He also writes for SitePoint's
...
1
Sara Smith is an ASP
...
She has been working with the
...
Sara just relocated to Belgium from the US with her family
...
He spent much of this time trying to convince Visual Basic developers that one of these days they would have to learn object oriented programming
...
sitepoint
...


About the Technical Director
As Technical Director for SitePoint, Kevin Yank oversees all of its technical publications—books, articles, newsletters, and blogs
...
Kevin lives in Melbourne, Australia, and enjoys performing improvised comedy
theatre and flying light aircraft
...
Visit http://www
...
com/ to access our books, newsletters, articles,
and community forums
...
lookwhostoxic
...

—Zak Ruvalcaba
To my family and friends
...
xi
1
...
NET and the
...
1
What is ASP
...
2
Installing the Required Software
...
6
Installing the
...
9
Configuring the Web Server
...
22
Installing SQL Server Management Studio Express
...
25
Writing your First ASP
...
26
Getting Help
...
32
2
...
NET Basics
...
NET Page Structure
...
36
Code Declaration Blocks
...
39
ASP
...
40
Server-side Comments
...
42
View State
...
47
ASP
...
48
Visual Basic
...
49
Summary
...
VB and C# Programming Basics
...
51
Control Events and Subroutines
...
56
Variables and Variable Declaration
...
62
Functions
...
68
Conditional Logic
...
72

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

Object Oriented Programming Concepts
...
77
Properties
...
81
Classes
...
81
Scope
...
83
Understanding Inheritance
...
NET
...
86
Using Code-behind Files
...
91
4
...
NET Web Pages
...
94
HTML Server Controls
...
97
Web Server Controls
...
103
List Controls
...
112
Web User Controls
...
126
Master Pages
...
135
Types of Styles and Style Sheets
...
141
5
...
143
Introducing the Dorknozzle Project
...
147
Meeting the Features
...
156
Using Visual Web Developer’s Built-in Web Server
...
160
Core Web Application Features
...
config
...
asax
...
173
Working with User Sessions
...
182

iv

Using Cookies
...

Preparing the Sitemap
...

Building the Master Page
...

Extending Dorknozzle
...

Debugging with Visual Web Developer
...

Custom Errors
...

Summary
...
Using the Validation Controls
...
NET Validation Controls
...
223
Using Validation Controls
...
230
CompareValidator
...
233
ValidationSummary
...
236
CustomValidator
...
242
Updating Dorknozzle
...
250
7
...
251
What is a Database?
...
254
Creating a New Database Using Visual Web Developer
...
256
Creating Database Tables
...
262
Column Properties
...
265
Creating the Employees Table
...
271
Populating the Data Tables
...
276

v

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

Foreign Keys
...

Implementing Relationships in the Dorknozzle Database
...

Summary
...
Speaking SQL
...
294
Using the SELECT Statement
...
299
Selecting Unique Data with DISTINCT
...
302
Selecting Ranges of Values with BETWEEN
...
304
Using the IN Operator
...
306
Limiting the Number of Results with TOP
...
307
Subqueries
...
309
Expressions and Operators
...
313
Arithmetic Functions
...
315
Date and Time Functions
...
318
The COUNT Function
...
319
Filtering Groups Using HAVING
...
322
Updating Existing Data
...
323
The UPDATE Statement
...
325
Stored Procedures
...
330
9
...
NET
...
NET
...
333
Defining the Database Connection
...
336

vi

Executing the Command
...

Reading the Data
...

Bulletproofing Data Access Code
...

Creating the Dorknozzle Employee Directory
...

Inserting Records
...

Deleting Records
...

Summary
...
Displaying Content Using Data Lists
...
402
Handling DataList Events
...
413
DataList and Visual Web Developer
...
424
Summary
...
Managing Content Using Grid View and Details View
...
428
Customizing the GridView Columns
...
436
Selecting Grid Records
...
445
Styling the DetailsView
...
452
Entering Edit Mode
...
459
Updating DetailsView Records
...
468
12
...
469
Using Data Source Controls
...
472
Binding the DetailsView to a SqlDataSource
...
489
More on SqlDataSource
...
494
What is a Data Set Made From?
...
NET 2
...

Implementing Paging
...

Implementing Sorting
...

Updating a Database from a Modified DataSet
...


498
504
506
509
520
521
526

13
...
527
Basic Security Guidelines
...
NET 2
...
530
Working with Forms Authentication
...
NET 2
...
544
Creating the Membership Data Structures
...
547
Using the ASP
...
552
Creating Users and Roles
...
556
Securing your Web Application
...
NET Login Controls
...
569
14
...
571
Writing and Reading Text Files
...
573
Writing Content to a Text File
...
580
Accessing Directories and Directory Information
...
586
Uploading Files
...
NET
...
595
Sending a Test Email
...
601
Summary
...
Web Control Reference
...
611
Properties
...
612
Standard Web Controls
...
613
BulletedList
...

Calendar
...

CheckBoxList
...
619
FileUpload
...
620
HyperLink
...
621
ImageButton
...
622
Label
...
623
ListBox
...
624
MultiView
...
625
PlaceHolder
...
625
RadioButtonList
...
627
Xml
...
628
CompareValidator
...
629
RangeValidator
...
631
RequiredFieldValidator
...
633
Navigation Web Controls
...
634
Menu
...
640
HTML Server Controls
...
644
HtmlButton Control
...
645
HtmlGeneric Control
...
647
HtmlInputButton Control
...
648
HtmlInputFile Control
...
NET 2
...

HtmlInputImage Control
...

HtmlInputText Control
...

HtmlTable Control
...

HtmlTableRow Control
...


650
651
652
653
653
655
656
657
658
Index
...
There’s nothing like the feeling you have after
you place your first dynamic web site online, and see your little toy in action
while other people are actually using it!
Web development with ASP
...
If you’ve never created
a dynamic web site before, I’m sure you’ll fall in love with this area of web development
...

ASP
...
Though it can take some time to learn, ASP
...
Whether you want to create simple web forms, or feature-rich
shopping carts, or even complex enterprise applications, ASP
...
All the tools you’ll need to get up and running are immediately available
and easy to install, and require very little initial configuration
...
NET,
teaching you the foundations step by step
...
To
demonstrate some of the more complex functionality, and to put the theory into
a cohesive, realistic context, we’ll develop a project through the course of this
book
...
NET in action, and to understand through
practice exactly how
...

We hope you’ll find reading this book an enjoyable experience that will significantly help you with your future web development projects!

Who Should Read this Book?
This book is aimed at beginner, intermediate, and advanced web designers looking
to make the leap into server-side programming with ASP
...
We expect that
you’ll already feel comfortable with HTML and a little CSS, as very little explanation of these topics is provided here
...
NET and the
...
NET pages, install and run SQL Server 2005, create

Preface

database tables, and work with advanced, dynamic ASP
...

All examples provided in the book are written in both Visual Basic and C#, the
two most popular languages for creating ASP
...
The examples start
at beginners’ level and proceed to more advanced levels
...
Experience with other programming or scripting languages (such as JavaScript) will certainly grease the wheels,
though, and should enable you to grasp fundamental programming concepts more
quickly
...
Read them from beginning to end
to gain a complete understanding of the subject, or skip around if you feel you
need a refresher on a particular topic
...
NET
Before you can start building your database-driven web presence, you must
ensure that you have the right tools for the job
...
NET Framework
...
Next,
we’ll walk through the installation of the Microsoft database solution: SQL
Server 2005
...
NET page to make sure that
everything’s running and properly configured
...
NET Basics
In this chapter, you’ll create your first useful ASP
...
We’ll explore
all of the components that make up a typical ASP
...
Then, we’ll walk through the process of deployment, focusing specifically on allowing the user to view the processing of a
simple ASP
...

Chapter 3: VB and C# Programming Basics
In this chapter, we’ll look at two of the programming languages that are used
to create ASP
...
You’ll learn about the syntax of the
two languages as we explore the concepts of variables, data types, conditionals,
loops, arrays, functions, and more
...


xii

Chapter 4: Constructing ASP
...
NET equivalent of web pages but, as we’ll see, the
process of building ASP
...
NET is bundled with hundreds of controls—including
HTML controls, web controls, and so on—that are designed for easy deployment within your applications
...
You’ll also learn about
master pages, which are a very exciting new feature of ASP
...
0
...
So it’s no surprise
that when we build web applications, we must consider more aspects than
when we build individual web forms
...
Next, we configure your web application, learn how to use the application state, user sessions, and cookies, explore
the process for debugging errors in your project, and more
...
With validation controls, Microsoft basically eliminated the headache of fumbling through, and configuring, tired, reused client-side validation scripts
...
Then, we’ll learn how
to perform more advanced validation using regular expressions and custom
validators
...
NET
...
Also in this chapter, we’ll begin to build the database for the
Dorknozzle intranet project
...
After a gentle introduction to the basic concepts
of SQL, which will teach you how to write SELECT, INSERT, UPDATE, and DELETE queries, we’ll move on to more advanced topics such as expressions,
conditions, and joins
...


xiii

Preface

Chapter 9: ADO
...
NET—the technology
that facilitates communication between your web application and the database
server
...
We’ll then help you begin the transition from working with
static applications to those that are database-driven
...
NET further, this chapter shows you how to utilize the DataList
control provided within the
...
DataLists play a crucial role
in simplifying the presentation of information with ASP
...
In learning
how to present database data within your applications in a cleaner and more
legible format, you’ll gain an understanding of the concepts of data binding
at a high level
...
NET: GridView and DetailsView
...
NET
1
...
DetailsView completes the picture by
offering us the functionality needed to display the details of a single grid
item
...
We’ll start by looking at direct data access
using ADO
...
We’ll then compare this approach
with that of using data sets to access data in a disconnected fashion
...

Chapter 13: Security and User Authentication
This chapter will show you how to secure your web applications with
ASP
...
We’ll discuss the various security models available, including IIS,
Forms, Windows, and Passport, and explore the roles that the Web
...
This chapter will also introduce you to the new
ASP
...
0 membership model, and the new ASP
...
0 login controls
...
Next, the chapter will show you how
to work with file streams to create text files, write to text files, and read from
text files stored on your web server
...
NET
...
NET
...
sitepoint
...


The Code Archive
As you progress through this book, you’ll note a number of references to the code
archive
...
You can get it from the book’s web site
...
Each folder contains
CS and VB subfolders, which contain the C# and VB versions of all the examples
for that chapter, respectively
...


Updates and Errata
No book is perfect, and we expect that watchful readers will be able to spot at
least one or two mistakes before the end of this one
...
NET and the
various web standards that apply
...
sitepoint
...
php

xv

Preface

The SitePoint Forums
If you’d like to communicate with us or anyone else on the SitePoint publishing
team about this book, you should join SitePoint’s online community
...
NET
forum, in particular, can offer an abundance of information above and beyond
the solutions in this book
...

It’s a good way to learn new stuff, get questions answered in a hurry, and just
have fun
...
In them, you’ll read
about the latest news, product releases, trends, tips, and techniques for all aspects
of web development
...
NET articles and tips,
but if you’re interested in learning other technologies, you’ll find them especially
valuable
...
sitepoint
...


Your Feedback
If you can’t find your answer through the forums, or if you wish to contact us
for any other reason, the best place to write is books@sitepoint
...
We have
a well-manned email support system set up to track your inquiries, and if our
support staff members are unable to answer your question, they will send it
straight to us
...


Acknowledgements
First and foremost, I’d like to thank the SitePoint team for doing such a great
job in making this book possible, for being understanding as deadlines inevitably
slipped past, and for the team’s personal touch, which made it a pleasure to work
on this project
...
sitepoint
...
sitepoint
...
php?f=141

Particular thanks go to Simon Mackie, whose valuable insight and close cooperation throughout the process has tied up many loose ends and helped make this
book both readable and accessible
...

Finally, returning home, I’d like to thank my wife Jessica, whose patience, love,
and understanding throughout continue to amaze me
...
Warm thanks and
gratitude go to my parents, my girlfriend, and my close friends for constantly
being there for me
...
NET and the

...
NET is one of the most exciting web development technologies on offer
today
...
Here was a powerful platform
with lots of built-in functionality, astonishing performance levels, and one of the
best IDEs (Integrated Development Environments) around: Visual Studio
...
NET showed the way for the faster, easier,
and more disciplined development of dynamic web sites, and the results were
impressive
...
NET has grown
...
NET 2
...

Not only that, but the basic versions of all development tools, including Visual
Web Developer 2005 Express Edition and SQL Server 2005 Express Edition, are
free!
This book shows you how to use all these technologies together in order to produce
fantastic results
...
Developers who have already
worked with earlier versions of ASP
...
NET 2
...

Let’s begin!

Chapter 1: Introducing ASP
...
NET Platform

What is ASP
...
Early in 2002, Microsoft
released a new technology for Internet development called ASP
...
ASP
...
It continues to offer flexibility in terms of language
support, but rather than a range of simple scripting languages, several fully-fledged
programming languages are now at the fingertips of ASP
...
Development in ASP
...

In the next few sections, we’ll introduce you to the basics of ASP
...
We’ll
walk through the process of installing it on your web server, and step through a
simple example that demonstrates how ASP
...
But first,
let’s define what ASP
...

ASP
...
NET Framework
...

ASP
...
Most web
designers start their careers learning client-side technologies like HTML, JavaScript, and Cascading Style Sheets (CSS)
...
The client
is entirely responsible for reading the markup in those files and interpreting that
markup to display the page on the screen
...
NET, are different
...
NET page) is
interpreted by the web server
...
NET, the code in the page is
read by the server and used to generate HTML, JavaScript, and CSS that is then
sent to the browser
...
NET code occurs on the
server, it’s called a server-side technology
...
1 shows, the client only
sees the HTML, JavaScript, and CSS
...


2

What is ASP
...
1
...


web client

This is the software program that the person uses to interact to
the web application
...


web server

This is the software program located on the server
...


ASP
...
A web application is just a
fancy name for a dynamic web site
...
Many different programming technologies and supported languages have been developed to create web applications; PHP, JSP, Ruby on Rails,

3

Chapter 1: Introducing ASP
...
NET Platform

CGI, and ColdFusion are just a few of the more popular ones
...
NET lets you write
web applications using a variety of familiar programming languages
...
NET uses the Microsoft
...
The
...

Even with all the jargon explained, you’re probably still wondering what makes
ASP
...
The truth is that there are many server-side technologies
around, each of which has its own strengths and weaknesses
...
NET has
a few features that really are unique:
❑ ASP
...
The
...
NET web sites
...

❑ ASP
...
In ASP
...
In ASP
...
The code is compiled into efficient binary
files, which can be run very quickly, again and again, without the overhead
involved in re-reading the page each time
...

❑ ASP
...
NET Framework
...
NET, which saves you from
having to reinvent the wheel
...
NET allows you to separate the server-side code in your pages from the
HTML layout
...

❑ ASP
...
During the course of this book, you’ll learn how to add powerful

4

Installing the Required Software

features to your web site, and to reuse them in many places with a minimum
of effort
...
NET web applications
...
In the course of
this book, you’ll learn how to use this tool to build the examples we discuss
...
NET Framework was first available only to the Windows platform, but
thanks to projects such as Mono,1 it’s since been ported to other operating
systems
...
NET, you first need to make sure you have all the
necessary software components installed and working on your system
...

Internet Information Services (IIS) or Cassini
IIS is the web server of choice for running ASP
...
You’ll
need your copy of the Windows CD to install and configure it
...
If you’re one of those users, there’s Cassini
...
NET web sites
...
When we come to use Visual Web Developer in Chapter 5,
we’ll be making use of that product’s built-in development web server, so not
having access to IIS on your system won’t be a problem
...
Any modern browser will
do
...
NET Framework 2
...
NET Framework drives ASP
...
When
you install the
...
mono-project
...
NET and the
...
NET
...
NET Framework already, as it
installs automatically through the Windows Update service
...
NET Framework Software Development Kit (SDK)
The
...
0 Software Development Kit (SDK) is a free download that contains the necessary Web Application development tools, a debugger for error correcting, and a suite of samples and documentation
...
In this book, we’ll use the following:
Microsoft SQL Server 2005 Express Edition
This is the free, but still fully functional, version of SQL Server 2005
...
You can read more on the differences between various
SQL Server 2005 editions at the Microsoft site
...


Installing the Web Server
Installing Internet Information Services (IIS)
IIS comes with most versions of server-capable Windows operating systems—including Windows 2000 Professional, Server, and Advanced Server; Windows XP
Professional; Windows XP Media Center Edition; and Windows Server 2003—but
it’s not installed automatically in all versions, which is why it may not be present
on your computer
...
If you run this, you’ll need to rely on Cassini,
which we discuss below
...
If the shortcut isn’t visible, then it’s not installed
...
microsoft
...
asp
To see this folder, you’ll need to view the Control Panel in “classic view
...


In the Control Panel, select Add or Remove Programs
...


Choose Add/Remove Windows Components
...


3
...
2
...
NET development, but you may want to click Details… to view the extra options you
could add
...
2
...


Click Next
...


Add Administrative Tools to the Start Menu
Here’s how to add Administrative Tools to the Windows XP Start menu:
1
...


2
...


7

Chapter 1: Introducing ASP
...
NET Platform

3
...

4
...


Once IIS is installed, close the Add or Remove Programs dialog
...
If you can, IIS is installed
...
3
...


Figure 1
...
The IIS administration tool

You can close this tool for now; you’ll meet it again later
...
Although we won’t cover the configuration of IIS for external use, we will show you how to configure IIS to support
local development of ASP
...


8

Installing the
...


Go to the Cassini download page
...


Download the Cassini installer executable (cassini
...


3
...
exe and follow the steps presented by the installer, accepting
the default options
...
Double-click CassiniWebServer
...
4
...
4
...
NET Framework and the Software Development Kit
first
...
NET Framework and the SDK
To begin creating ASP
...
NET Framework and the Software Development Kit (SDK)
...
NET Framework includes
4

http://www
...
net/Projects/Cassini/Download/

9

Chapter 1: Introducing ASP
...
NET Platform

the files necessary to run and view ASP
...


Installing the
...
NET Framework is to download and install it
directly from the Web
...
To check, open the folder
C:\WINDOWS\Microsoft
...
If this folder
doesn’t exist, you definitely don’t have the
...
If it does
exist, you should find inside it at least one folder with a name like v1
...
4322
...
NET Framework
you have installed
...
NET Framework
...
NET Framework, simply follow the steps
outlined below:
1
...
NET support site5 and click the Download the
...


2
...
NET Framework Version 2
...
Remember, we’ll install
the redistributable package first, then the SDK
...


3
...


4
...
After the download is complete, doubleclick the executable to begin the installation
...


Follow the steps presented by the wizard until installation completes
...
asp
...


Go back to the ASP
...
NET
Framework link again
...


This time, click the appropriate download link under the
...
0 Software Development Kit heading
...


3
...


4
...


5
...
Before you do so, I strongly recommend that you close all other
programs to ensure the install proceeds smoothly
...


Follow the steps outlined by the
...
When asked for setup options, it’s safe to use the default values
...


A Big Download!
The
...


Configuring the Web Server
Configuring IIS
After installing the
...
NET
...


Open the command prompt by selecting Start > All Programs > Microsoft

...
0 > SDK Command Prompt
...


Type the following command to install ASP
...
0>aspnet_regiis
...
NET (2
...
50727)
...

Finished installing ASP
...
0
...


11

Chapter 1: Introducing ASP
...
NET Platform

3
...
NET is installed, close the command prompt and check again to
confirm that ASP
...


Running aspnet_regiis
...
NET may already have been installed
for you, but running aspnet_regiis
...
Also, remember that
you need to run this utility again in case you reinstall IIS
...
NET
Framework to coerce Cassini into working as it should
...


Open the command prompt by selecting Start > All Programs > Microsoft

...
0 > SDK Command Prompt
...


Enter the following command at the prompt:
C:\Program Files\…\SDK\v2
...
dll
Microsoft (R)
...
Version 2
...
All rights reserved
...


Where do I Put my Files?
IIS Recommended
From here on in, the instructions we provide will be centered around IIS, as
Cassini isn’t suitable for production environments
...
Where needed, Cassini instructions will be given, but IIS
will receive the bulk of the discussion
...
NET up and running, let’s find out where the files for
your web applications are kept on the computer
...
By default, IIS maps the C:\Inetpub\wwwroot folder of your disk
to your web site’s root directory, which is generally considered a good repository
for storing and managing your web applications
...
5, you’ll notice that the files and folders are the same (some
extra items will be listed in IIS; we’ll look at these shortly)
...

We’ll see more on this soon
...
5
...
If you’ve been developing web pages for a long time, habit may drive
you to open files directly in your browser by double-clicking on the HTML files
...
NET is a server-side language, your web server needs to
have a crack at the file before it’s sent to your browser for display
...
NET code won’t be converted into HTML
that your browser can understand
...
NET files can’t be opened
directly from the disk using Windows Explorer
...
If you try this now, IIS will open up a
default help page (although this behavior will vary depending on the settings of

13

Chapter 1: Introducing ASP
...
NET Platform

your Windows installation; for example, if you get an error instead of the default
help page, don’t worry)
...

To see this in practice, create a new file named index
...
htm

...
w3
...
dtd">


Simple HTML Page


This is a simple HTML page
...
htm, as shown in Figure 1
...


Figure 1
...
Testing IIS

Experiencing an Error?
If the page doesn’t load as illustrated in Figure 1
...
You might want to double-check that you correctly followed the
steps for installing it, and re-check the IIS configuration procedure
...
com
...


14

Configuring the Web Server

This localhost name is equivalent to the so-called loopback IP address, 127
...
0
...
0
...
1/index
...
If you know them, you can also use the name or IP address of your
machine to the same end
...
This occurs because
you’re no longer using your local authentication, which is implicit with localhost
...
NET installed, let’s look at
how you can start, stop, and restart IIS if the need arises
...
Also, some
external programs may stop IIS upon launch because of potential security
vulnerabilities, so you’ll need to start it again yourself
...
Alternatively, after selecting Default Web Site, you can use the Stop, Pause,
and Play icons from the toolbar
...
For instance,
imagine your company has a web server that serves documents from C:\Inetpub\wwwroot
...
example
...
If you create a subfolder of wwwroot, named about, files in that
directory can be accessed via http://www
...
com/about/
...
If, for instance, you were developing another
web application, you could store the files for it in C:\dev\OrderSystem
...
This new site would then be accessible through the URL
http://www
...
com/order/
...

By default, a virtual directory, called IISHelp, is preconfigured in IIS; it maps to
c:\windows\help\iishelp
...
7 that IISHelp contains

15

Chapter 1: Introducing ASP
...
NET Platform

subdirectories called common and iis—these are physical folders inside c:\windows\help\iishelp
...
7
...


2
...
htm file you created earlier into your newly created Learning
folder
...


In the Internet Information Services management console, right-click Default
Web Site and select New > Virtual Directory
...
Click Next
...


You need to choose an alias for your virtual directory: enter Learning, then
click Next
...


16

First, you need to create on your disk a folder to which your virtual directory
will be mapped
...
We’ll use this folder, C:\WebDocs\Learning, for various exercises in
this book
...
Click Next
...


In the next screen, you can select permissions settings for your directory
...
Click Next
...


Click Finish
...
8 illustrates
...
8
...


Load this link by entering http://localhost/Learning/index
...
If everything went well, you should see your
little HTML page load, as has the one in Figure 1
...


Figure 1
...
Testing your new virtual directory

Note that by loading the page through the HTTP protocol, your request goes
through IIS
...
htm is a simple HTML page that doesn’t need any
server-side processing, you can also load it directly from the disk
...
NET and the
...
NET scripts you’ll see through the rest of this
book
...
8
...

As index
...

To see and edit the default document names for a virtual directory (or any directory, for that matter), you can right-click the directory’s name in the IIS management console, click Properties, and select the Documents tab
...
10
...
10
...
htm or
default
...
If there is no index page, IIS assumes we want to see the contents
of the requested location
...
You’ll find that option in the
Directory tab of the Properties window
...
Allowing visitors to freely see and access all the files and directories that make
up your web page is not only a little messy and unprofessional, but also increases the potential for security issues (you don’t want any hackers to stick
their nose into your code, do you?)
...
htm
isn’t there, ready to be served to the visitor, a message reading “Directory
Listing Denied” will be served instead
...
The
Properties dialog that we’ve just used lets us configure various useful properties,
including:
Virtual Directory

This option allows you to configure directory-level
properties, including path information, the virtual
directory name, access permissions, etc
...


Documents

This option allows you to configure a default page that
displays when the user types in a full URL
...
aspx is listed as a default
page, the user need only enter http://www
...
com/, rather than http://www
...
com/default
...
You can
easily change and remove these default pages by selecting the appropriate button to the right of the menu
...


HTTP Headers

This option gives you the ability to forcefully control
page caching on the server, add custom HTTP Headers,
Edit Ratings (this helps identify the content your site
provides to users), and create MIME types
...


19

Chapter 1: Introducing ASP
...
NET Platform

Custom Errors

This option allows you to define your own custom error
pages
...


ASP
...
NET applications stored in that folder
...


Using Cassini
If you’re stuck using a version of Windows that doesn’t support IIS, you’ll need
to make use of Cassini to get your simple ASP
...
Cassini doesn’t support virtual directories, security settings, or any of
IIS’s other fancy features; it’s just a very simple web server that gives you the
basics you need to get up and running
...


Create a directory called C:\WebDocs\Learning, just like the one we created
in the section called “Virtual Directories”
...


Copy index
...
We first saw index
...


3
...
exe
...


Cassini has just three configuration options:
Application Directory
It’s here that your application’s files are stored
...

Server Port
Web servers almost always operate on port 80, so we won’t touch this
setting
...
By default, it’s set to /, meaning that you can access the
file C:\WebDocs\Learning\index
...
htm
...
htm
...

5
...


6
...
11
...
11
...
htm straight
away—you’ll be presented with a list of files instead
...
htm or default
...


21

Chapter 1: Introducing ASP
...
NET Platform

Installing SQL Server 2005 Express Edition
After making sure IIS, the
...

SQL Server 2005 is Microsoft’s database solution for medium to large companies
and enterprises
...

For the examples in this book, we’ll use SQL Server 2005 Express Edition, which
is free and sufficiently powerful for our needs
...

You can install SQL Server 2005 Express Edition as follows:
1
...
microsoft
...


2
...
The former
will be fine for our purposes
...


3
...
It’s safe to use the default
options all the way through, though it is a rather long process
...
Like IIS, SQL Server runs as a service in
the background, accepting connections to databases instead of web pages
...


Installing SQL Server Management Studio Express
In order to use your SQL Server 2005 install effectively, you’ll need some sort
of administration tool that will allow you to work with your databases
...

To install SQL Server Management Studio Express, follow these steps:
1
...
microsoft
...


2
...


3
...


Once it’s installed, SQL Server Manager Express can be accessed from Start > All
Programs > Microsoft SQL Server 2005 > SQL Server Management Studio Express
...
12 illustrates
...
12
...
Because you’re the user that
installed SQL Server 2005, you’ll already have full privileges to the SQL Server
...


23

Chapter 1: Introducing ASP
...
NET Platform

Figure 1
...
Managing your database server

After you’re authenticated, you’ll be shown the interface in Figure 1
...

SQL Server Management Studio lets you browse through the objects inside your
SQL Server, and even modify their settings
...
14
...
How is this useful? Imagine
you have a production server that runs two applications with two separate
databases on the same instance of SQL Server
...
If the
second application’s database was operating on a second instance of SQL
Server, we wouldn’t have such a problem—the second application would
continue working without missing a beat
...
The default instance name for
SQL Server 2005 Express Edition is SQLEXPRESS
...
14
...
You can see this specification back in Figure 1
...
13,
where we’re connecting to an instance called SQLEXPRESS on a computer
called VM2
...
For the
first exercises in this book, we’ll recommend you use a simple text editor such as

25

Chapter 1: Introducing ASP
...
NET Platform

Notepad, but you’ll gradually learn how to use Visual Web Developer to ease
some of the tasks we’ll tackle
...

1
...
microsoft
...


2
...


3
...
At one point, you’ll be asked about installing
Microsoft MSDN 2005 Express Edition, which is the product’s documentation
...
(Note that you’ve already installed the
...
0 documentation, together with the SDK
...
NET Framework 2
...


In this book, we’ll start using Visual Web Developer to build real web applications
in Chapter 5
...


Writing your First ASP
...
NET exercise, we’ll create the simple example shown in Figure 1
...


Figure 1
...
Your first ASP
...
NET Page

Let’s get started! Open your text editor (Notepad is fine)
...
NET pages automatically, such as Visual Studio
...
NET works
...
aspx in the
Learning folder you created earlier
...
aspx by entering
the HTML for our page, shown below:
File: FirstPage
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
NET 2
...
NET code that will create the
dynamic elements of the page, starting with the time
...
aspx (excerpt)

...
w3
...
dtd">


My First ASP<br> ...<br> 0 Page


Hello there!


The time is now:





We’ve added an tag to the document
...
The asp: part of the tag name
identifies it as a built-in ASP
...
ASP
...


27

Chapter 1: Introducing ASP
...
NET Platform

The runat="server" attribute identifies the tag as something that needs to be
handled on the server
...
NET sees it
and converts it to regular HTML tags before the page is sent to the browser
...
NET to replace this particular tag
with the current time
...
ASP
...
The two most common
languages are VB and C#
...
Here’s a
version of the page in VB:
Visual Basic

File: FirstPage
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
NET Page


28

Writing your First ASP
...
If you type the case of a letter
incorrectly, the page won’t load
...


Both versions of the page achieve exactly the same thing
...
If you’ve never
done any server-side programming before, the code may look a little scary
...
Using
your web browser, load http://localhost/Learning/FirstPage
...

Whether you load the C# version or the VB version, the output should look like
Figure 1
...


No Time?
If the time isn’t displayed in the page, chances are that you opened the file
directly in your browser instead of loading it through your web server
...
NET is a server-side language, your web server needs to process the file
before it’s sent to your browser for display
...
NET code is never converted into HTML that your browser can
understand, so make sure you load the page by entering an actual HTTP
URL (such as http://localhost/Learning/FirstPage
...
aspx)
...

File: FirstPage
...
Like
the tag, this

The End Sub in the VB code, and the } in the C# code, mark the end of the
script that’s to be run when the page is loaded, and the tag marks the
end of the script block
...
NET generated
for you
...
Here’s what you’ll see:
...
w3
...
dtd">


My First ASP<br> ...<br> NET code has gone! Even the script block has been<br />completely removed, and the <asp:Label/> tag has been replaced by a <span><br />tag (which has the same id attribute as the <asp:Label/> tag we used) that<br />contains the date and time<br> ...<br> NET and the <br> ...<br> NET works<br> ...<br> NET page; it’s just plain HTML like any other<br> ...<br> NET code is run by your web server and converted to plain HTML that’s<br />sent to the browser<br> ...<br> The<br />next chapter will get a bit more challenging as we investigate some valuable programming concepts<br> ...<br> NET web applications, you will undoubtedly have questions<br />that need answers, and problems that need to be solved<br> ...<br> NET support<br />web site7 was developed by Microsoft as a portal for the ASP<br> ...<br> NET<br> ...<br> You can also ask questions of the<br />experienced community members in the SitePoint Forums<br> ...<br> NET<br> ...<br> NET and that it’s a part of the <br> ...<br> <br />First, you learned about the components of ASP<br> ...<br> NET Framework<br> ...<br> NET development<br> ...<br> NET! The next chapter<br />will build on this knowledge as we begin to introduce you to ASP<br> ...<br> <br /><br />7<br />8<br /><br />32<br /><br />http://www<br> ...<br> net/<br />http://www<br> ...<br> com/forums/<br /><br /> 2<br /><br />ASP<br> ...<br> NET is, and what it can do<br> ...<br> NET<br />page<br> ...<br> NET at more advanced levels<br> ...<br> But before you can<br />begin to develop applications with ASP<br> ...<br> NET page—with this knowledge, you’ll be able to<br />identify the parts of the ASP<br> ...<br> So, in this chapter, we’ll talk about some key mechanisms<br />of an ASP<br> ...<br> NET Basics<br /><br />We’ll also cover two of the “built-in” languages supported by the <br> ...<br> As this section progresses, we’ll explore the differences and<br />similarities between these two languages, and get a clear idea of the power that<br />they provide to those creating ASP<br> ...<br> <br />So, what exactly makes up an ASP<br> ...<br> NET page<br> ...<br> NET Page Structure<br />ASP<br> ...<br> aspx file name extension,<br />and can be placed on any web server equipped with ASP<br> ...<br> <br />When a client requests an ASP<br> ...<br> NET runtime, a program that runs on the web server that’s responsible for<br />reading the page and compiling it into a <br> ...<br> This class is then used to<br />produce the HTML that’s sent back to the user<br> ...<br> NET class can respond directly to the<br />request, producing the page’s HTML and sending it to the client, until such time<br />as the <br> ...<br> This process is illustrated in Figure 2<br> ...<br> <br />An ASP<br> ...<br> NET server controls<br />❑ server-side comments<br />❑ literal text and HTML tags<br />Figure 2<br> ...<br> NET page<br> ...<br> NET Page Structure<br /><br />Figure 2<br> ...<br> The life cycle of the ASP<br> ...<br> 2<br> ...<br> NET page<br /><br />35<br /><br /> Chapter 2: ASP<br> ...<br> aspx within the Learning virtual directory you created<br />in Chapter 1<br> ...<br> aspx<br />should render the result shown in Figure 2<br> ...<br> <br /><br />Figure 2<br> ...<br> Sample Page in action<br /><br />As you can see, this ASP<br> ...<br> NET page<br> ...<br> <br /><br />Directives<br />The directives section is one of the most important parts of an ASP<br> ...<br> <br />Directives control how a page is compiled, specify how a page is cached by web<br />browsers, aid debugging (error-fixing), and allow you to import classes to use<br />within your page’s code<br> ...<br> This is followed by the<br />directive name, plus any attributes and their corresponding values<br> ...<br> <br />There are many directives that you can use within your pages, and we’ll discuss<br />them in greater detail later, but, for now, know that the Import and Page directives<br />are the most useful for ASP<br> ...<br> Looking at the sample ASP<br> ...<br> 2, we can see that a Page directive was used at the top of the<br />page like so:<br />Visual Basic<br /><br /><%@ Page Language="VB" %><br /><br />36<br /><br />File: Hello<br> ...<br> aspx (excerpt)<br /><br /><%@ Page Language="C#" %><br /><br />In this case, the Page directive specifies the language that’s to be used for the<br />application logic by setting the Language attribute<br> ...<br> A<br />whole range of different directives is available; we’ll see a few more later in this<br />chapter<br> ...<br> NET directives can appear anywhere on a page, but they’re<br />commonly included at its very beginning<br> ...<br> NET page’s HTML<br> ...<br> NET page<br> ...<br> In our page, we’ve placed the code<br />inside <script> tags, like so:<br />Visual Basic<br /><br /><script runat="server"><br />Sub mySub()<br />' Code here<br />End Sub<br /></script><br /><br />Here, the tags enclose VB code, but it could just as easily be C#:<br />C#<br /><br /><script runat="server"><br />void mySub()<br />{<br />// Code here<br />}<br /></script><br /><br />Comments in VB and C# Code<br />Both of these code snippets contain comments—explanatory text that will be ignored by ASP<br> ...<br> <br /><br />37<br /><br /> Chapter 2: ASP<br> ...<br> <br />In C# code, two slashes (//) achieve the same end<br> ...<br> NET emerged, ASP also supported such script tags using a runat="server" attribute<br> ...<br> <br />Code declaration blocks are generally placed inside the head of your ASP<br> ...<br> The sample ASP<br> ...<br> 2, for instance, contains the<br />following code declaration block:<br />Visual Basic<br /><br />File: Hello<br> ...<br> Text = "Hello World"<br />End Sub<br /></script><br /><br />Perhaps you can work out what the equivalent C# code would be:<br />C#<br /><br />File: Hello<br> ...<br> Text = "Hello World";<br />}<br /></script><br /><br />The <script runat="server"> tag also accepts two other attributes<br> ...<br> NET<br />page will use the language provided by the language attribute of the Page directive<br> ...<br> <br />The second attribute that’s available to us is src; this lets us specify an external<br />code file for use within the ASP<br> ...<br> vb"><br />C#<br /><br /><script runat="server" language="C#" src="mycodefile<br> ...<br> <br />You can use code render blocks to define inline code or expressions that will<br />execute when a page is rendered<br> ...<br> <br />On the other hand, code within a code declaration block (within <script> tags)<br />is executed only when it is called or triggered by user or page interactions<br> ...<br> NET page<br> ...<br> In our example, the following<br />is a code render block:<br />Visual Basic<br /><br />File: Hello<br> ...<br> " %><br />C#<br /><br />File: Hello<br> ...<br> "; %><br /><br />39<br /><br /> Chapter 2: ASP<br> ...<br> <br />Inline expression render blocks can be compared to Response<br> ...<br> They start with <%= and end with %>, and are used to display the values of<br />variables and methods on a page<br> ...<br> aspx (excerpt)<br /><br /><%= Title %><br /><br />If you’re familiar with classic ASP, you’ll know what this code does: it simply<br />outputs the value of the variable Title that we declared in the previous inline<br />code block<br> ...<br> NET Server Controls<br />At the heart of any ASP<br> ...<br> There are three basic types of server<br />control: ASP<br> ...<br> <br />Usually, an ASP<br> ...<br> Controls offer the following advantages to ASP<br> ...<br> <br />❑ ASP<br> ...<br> We’ll be covering view state later in this chapter<br> ...<br> When<br />the response comes back to the client, text box entries, drop-down list selections, and so on, are all retained through view state<br> ...<br> NET controls, developers are able to separate a page’s presentational<br />elements (everything the user sees) from its application logic (the dynamic<br />portions of the ASP<br> ...<br> <br />❑ Many ASP<br> ...<br> <br /><br />40<br /><br /> Server-side Comments<br /><br />ASP<br> ...<br> In particular, Chapter 4 explains many of the controls<br />that ship with ASP<br> ...<br> For now, though, let’s continue with our dissection of<br />an ASP<br> ...<br> <br /><br />Server-side Comments<br />Server-side comments allow you to include within the page comments or notes<br />that will not be processed by ASP<br> ...<br> Traditional HTML uses the <!-- and -> character sequences to delimit comments; any information included between<br />these tags will not be displayed to the user<br> ...<br> NET comments look very similar,<br />but use the sequences <%-- and --%><br> ...<br> NET example contains the following server-side comment block:<br />File: Hello<br> ...<br> NET comments and HTML comments is that<br />ASP<br> ...<br> NET code<br> ...<br> "; %><br /><%= Title %><br />--><br /><br />Here, it looks as if a developer has attempted to use an HTML comment to stop<br />a code render block from being executed<br> ...<br> NET runtime<br> ...<br> NET, and the value of the variable Title will be<br />sent to the browser inside an HTML comment, as shown here:<br /><!–This code generated by a code render block<br> ...<br> NET Basics<br /><br />C#<br /><br /><%-<% string Title = "This is generated by a code render block<br> ...<br> NET runtime will ignore the contents of this comment, and the value<br />of the Title variable will not be output<br> ...<br> NET page are plain old text and HTML<br> ...<br> NET controls and code in a way that’s suitable for users<br> ...<br> 2:<br />Visual Basic<br /><br />File: Hello<br> ...<br> 0 Strict//EN"<br />"http://www<br> ...<br> org/TR/xhtml1/DTD/xhtml1-strict<br> ...<br> Text = "Hello World!"<br />End Sub<br /></script><br /></head><br /><body><br /><form runat="server"><br /><p><br /><asp:Label id="messageLabel" runat="server" /><br /></p><br /><p><br /><%-- Declare the title as string and set it --%><br /><% Dim Title As String = "This is generated by a " & _<br />"code render block<br> ...<br> aspx (excerpt)<br /><br /><%@ Page Language="C#" %><br /><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1<br> ...<br> w3<br> ...<br> dtd"><br /><html><br /><head><br /><title>Sample Page





Text="Click Me" OnClick="Click" />




C#

File: ViewState
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
Text = nameTextBox
...
NET Basics


Text="Click Me" OnClick="Click" />





In this case, the code uses ASP
...

As you can see in Figure 2
...


Figure 2
...
ASP
...
But where’s all that information
stored? ASP
...
View the source of the page after you’ve submitted the form,
and look for the following code:
value="/wEPDwUKLTEwNDY1Nzg0MQ9…0fMCR+FN5P6v5pkTQwNEl5xhBk" />

This is a standard HTML hidden form field
...

View state is enabled for every page by default
...
To do this, set the EnableViewState property of the Page directive to
false:
<%@ Page EnableViewState="False" %>

46

Working with Directives

Disabling View State, Control by Control
View state can also be disabled for particular controls in a page: simply set
their EnableViewState property to false
...


Speaking of directives, it’s time to take a closer look at these curious beasts!

Working with Directives
For the most part, ASP
...
In essence, just using the
...
NET Framework for processing
...

We talked a little about directives and what they can do earlier in this chapter
...
Three of the most commonly used directives are:
Page

This directive defines page-specific attributes for the ASP
...
We’ve already seen this directive in
use
...
The following example, for instance, imports functionality from the System
...
Mail namespace, which you could use to send
email from a page
...
NET’s way of keeping all its
functionality neatly organized—we’ll see how they work in Chapter 3
...
Web
...

Register

This directive allows you to register a user control for use on your page
...
NET Basics

<%@ Register TagPrefix="uc" TagName="footer"
Src="footer
...
NET Languages
As we saw in the previous chapter,
...
If you’re
used to writing ASP, you may think the choice of VBScript or JScript would be
an obvious one
...
NET, Microsoft did away with VBScript, merging
it with Visual Basic
...
NET’s support for C# is likely to find favor with developers from other backgrounds
...
By the end
of this section, you will, I hope, agree that the similarities between the two are
astonishing—any differences are minor and, in most cases, easy to figure out
...
For instance, old-style CGI scripts were typically
written with Perl or C/C++, JSP uses Java, Coldfusion uses CFML, and PHP is
a technology and a language rolled into one
...
To keep things simple, this
book will consider the two most popular: VB and C#
...


Visual Basic
The latest version of Visual Basic is the result of a dramatic overhaul of Microsoft’s
hugely popular Visual Basic language
...
The latest version of VB has many advantages over older versions, most notably the fact that it has now became a fully object oriented language
...
Despite the changes, VB generally stays close to the
structured, legible syntax that has always made it so easy to read, use, and
maintain
...
However, there’s little doubt that its development was at least
hurried along by Microsoft’s legal disputes with Sun
...
We’re not going to worry about J# here, as
C# is preferable
...


Summary
In this chapter, we started out by introducing key aspects of an ASP
...
As the chapter progressed, we took a closer look at the two
most popular languages that ASP
...

In the next chapter, we’ll create a few more ASP
...


49

50

3

VB and C# Programming Basics

As you learned at the end of the last chapter, one of the great things about using
ASP
...
NET languages
we like
...
We’ll start by discussing some basic
concepts of programming ASP
...

We’ll explore programming fundamentals such as variables, arrays, functions,
operators, conditionals, loops, and events, and work through a quick introduction
to object oriented programming (OOP)
...

The final sections of the chapter cover some of the ideas underlying modern, effective ASP
...
We finish with an examination of
how object oriented programming techniques impact the ASP
...


Programming Basics
One of the building blocks of an ASP
...
To get anywhere with
ASP
...
All ASP
...
Each of these controls

Chapter 3: VB and C# Programming Basics

allows the user to interact with the application in some way: checking checkboxes,
scrolling through lists, selecting list items, and so on
...
It is by handling these events
within our code that we get ASP
...

For instance, imagine that a user clicks a button on an ASP
...
That
button (or, more specifically, the ASP
...
A method called an event handler executes
automatically when an event is raised—in this case, the event handler code performs a specific action for that button
...

Events really are the key to ASP
...

It wouldn’t be practical, or even necessary, to cover all aspects of VB and C# in
this book, so we’re going to discuss enough to get you started, and complete this
chapter’s projects and samples using both languages
...
NET
...
For instance,
the code below creates a server-side button and label
...
If you want to test the code, save the file in the
Learning virtual directory you’ve been using for the other examples
...
aspx (excerpt)

...
w3
...
dtd">


Click the Button



OnClick="button_Click" Text="Click Me" />





52

Control Events and Subroutines

When the button’s clicked, it raises the Click event, and ASP
...
In the code above, we told ASP
...
aspx (excerpt)


Click the Button









You can see that the event handlers (the functions that are executed to handle
the events) aren’t specifically defined anywhere
...
NET page, and their
handlers have the default names that we’ve used in the code (Page_Init,
Page_Load, etc)
...
Within
each event’s event handler, we’ve added a message to the Label control; this will
give us visual proof that the events actually fire in order
...
2
...
This is because, at
that point, the HTML output has already been generated and sent to the browser
...
However,
in certain situations the other events will be helpful as well
...
NET supports other events, which we haven’t covered here
...


58

Variables and Variable Declaration

Figure 3
...
Handling ASP
...
Basically, variables let you give a name, or identifier,
to a specific piece of data; we can then use that identifier to store, modify, and
retrieve the data in question
...
NET Framework
...
There are many different kinds
of data types, including strings, integers (whole numbers), and floating point
numbers (fractions or decimals)
...
” In VB, we use the keyword Dim, which
stands for “dimension,” while in C#, we simply precede the variable name with
the appropriate data type
...
This practice isn’t recommended, though, as it makes the code more
difficult to read
...
1 lists the most useful data types available in VB and C#
...
1
...


Many Aliases are Available
These data types are the VB- and C#-specific aliases for types of the
...
For example, instead of Integer or int, you could use
System
...
NET language; likewise, instead of Boolean or bool,
you could use System
...


60

Variables and Variable Declaration

To sum up, once you’ve declared a variable as a given type, it can only hold data
of that type: you can’t put a string into an integer variable, for instance
...

Have a look at this code:
Visual Basic

Dim intX As Integer
Dim strY As String = "35"
intX = strY + 6
C#

int intX;
string strY = "35";
intX = strY + 6;

Now, you or I might think that this could make sense—after all, the string strY
contains a number, so we might wish to add it to another number
...
The VB version of the code will execute
without a hitch, because the string will be converted to a number before the
mathematical operation is applied
...

As a rule of thumb, it’s better to stay on the safe side and avoid mixing types
wherever possible
...
Strongly typed languages are those that are very
strict about data types
...
For example, if you try to sum a
number with a string, as we did in the previous code snippet, the JavaScript
interpreter would make the conversion for you automatically
...


In
...
Parse(strY) + 6
C#

int intX;
string strY = "35";
intX = Convert
...
This principle holds true whenever we’re mixing types in a single expression
...
Any one item in an array can be accessed using the array’s
name, followed by that item’s position in the array (its offset)
...
The results of this code are shown in Figure 3
...
aspx

...
w3
...
dtd">


Arrays








C#

File: Functions
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
NET Functions









72

Loops

C#

File: Loops
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
Text = counter
...
5
...
5
...
Of course, since all this happens in Page_Load (i
...
before
any output is sent to the browser), you’ll only see the last value assigned: 10
...
Try
changing the code so that the counter variable is initialized to 20 instead of 0
...

The other form of the While loop, called a Do While loop, checks whether or not
the condition has been met at the end of the code block, rather than at the beginning:
Visual Basic

File: Loops
...
Text = counter
...
aspx (excerpt)

void Page_Load()
{
// initialize counter
int counter = 0;
// loop
do
{
// Update the label
messageLabel
...
ToString();
// C# has the operator ++ to increase a variable by 1
counter++;
}
while (counter <= 10);
}

If you run this code, you’ll see it provides the exact same output we saw when
we tested the condition before the code block
...

In this case, we will, in fact, see 20 displayed, because the loop code is executed
once before the condition is even checked! There are some instances when this

74

Loops

is just what we want, so being able to place the condition at the end of the loop
can be very handy
...
The following example displays
the count of items within a DropDownList control called productList:
Visual Basic

Dim i As Integer
For i = 1 To productList
...
Count
messageLabel
...
ToString()
Next
C#

int i;
for (i = 1; i <= productList
...
Count; i++)
{
messageLabel
...
ToString();
}

In VB, the loop syntax specifies the starting and ending values for our counter
variable within the For statement itself
...
Items
...
While this allows for some powerful variations on the theme in our C#
code, it can be confusing at first
...

The other type of For loop is For Each, which loops through every item within
a collection
...
Text = item
Next
C#

foreach (string item in arrayName)
{
messageLabel
...

In these cases, you would use either Exit, if your code is in VB, or the equivalent
(break) statement in C#, to terminate the loop:
Visual Basic

Dim i As Integer
For i = 0 To 10
If (i = 5) Then
Response
...
Write("Oh no! Not the number 5!!");
break;
}
}

In this case, as soon as our For loop hits the condition i = 5, it displays a
warning message using the Response
...

Although we’ve only scratched the surface, VB and C# provide a great deal of
power and flexibility to web developers, and time spent learning the basics now
will more than pay off in the future
...
The code can be separated into
modules, each of which defines classes that can be imported and used in other
modules
...

One of the reasons why these languages are so powerful is that they facilitate
object oriented programming (OOP)
...
This section will
provide a basic OOP foundation angled towards the web developer
...


Objects and Classes
So what does the term “object oriented programming” mean? Basically, as the
name suggests, it’s an approach to development that puts objects at the center
of the programming model
...

In programming, an object's state is described by its fields and properties, while
its behavior is defined by its methods and events
...

We often use objects in our programs to describe real-world objects—we can have
objects that represent a car, a customer, a document, or a person
...

It’s very important to have a clear understanding of the difference between a
class and an object
...
I just said that you could have objects of type

77

Chapter 3: VB and C# Programming Basics

Car, for example
...

The class defines the behavior of all objects of that type
...
However,
each individual Car object may be in a different gear at any particular time; thus,
each object has its own particular state
...
The class defines the behavior of the objects—they’re numeric, and we can perform mathematical operations on
them—and the instances of objects (age and height) have their behavior defined
by the class to which they belong, but they also hold state (so age could be 20)
...
In C#, we first mention the type of the object,
then we name that particular instance
...

Object oriented programming sounds like an advanced topic, but getting started
with it is actually very easy, because OOP offers us a natural way to conceive and
design programs
...
In OOP,
one thinks of programming problems in terms of objects, properties, and methods
...

For the examples that follow, we’ll use as our example my dog, an Australian
Shepherd named Rayne
...
You might describe
him in terms of his physical properties: he’s gray, white, brown, and black, stands
roughly one-and-a-half feet high, and is about three feet long
...

So, if we were to represent Rayne in an OOP program, we’d probably start by
creating a class called Dog
...
When we define a class, we must define the
following two items:
Properties

Properties hold specific information relevant to that class of object
...
Our Dog class might have properties such as Color,
Height, and Length
...
Methods are subroutines (if they don’t return a value) or
functions (if they do) that are specific to a given class
...


Once we’ve defined a class, we can write code that creates objects of that class,
using the class a little like a template
...

So, we might create an instance of our Dog class called rayne, set its properties
accordingly, and use the methods defined by the class to interact with Rayne, as
shown in Figure 3
...


Figure 3
...
An instance of Dog

79

Chapter 3: VB and C# Programming Basics

This is just a simple example to help you visualize what OOP is all about
...


Properties
As we’ve seen, properties are characteristics shared by all objects of a particular
class
...
NET Button class exposes properties including:
❑ Width
❑ Height
❑ ID
❑ Text
❑ ForeColor
❑ BackColor
Unfortunately for me, if I get sick of Rayne’s color, I can’t change it in real life
...
NET object, we could change any of his properties in
the same way that we set variables (although a property can be read-only or writeonly)
...
Color = "Brown"
C#

rayne
...
We use
the dot operator (
...
"

Methods
With our dog example, we can make a particular dog do things by calling commands
...
If I want Rayne to lie down, I tell
him to lie down
...
For example, to
make Rayne sit, we would use the following code to call his Sit method:
Visual Basic

rayne
...
Sit();

Given that rayne is an instance of our Dog class, we say that the Sit method is
exposed by the Dog class
...
When you create an instance of a class, you are creating an object
of that class, and the new object has all the characteristics and behaviors (properties and methods) defined by the class
...
6 illustrated
...

In OOP, when we create new instances of a class, we say we’re instantiating

81

Chapter 3: VB and C# Programming Basics

that class
...

At least one constructor will be defined for most of the classes you will write
(though we can define more than one constructor for a class, as we’ll see shortly),
since it’s likely that some data will need to be initialized for each class at creation
time
...


Scope
You should now understand programming objects to be entities that exist in a
program and are manipulated through the methods and properties they expose
...

Imagine we’re writing the Sit method inside this class, and we realize that before
the dog can sit, it has to shuffle its back paws forward a little (bear with me on
this one!)
...
However, we don’t want code in an ASP
...
We can prevent it
by controlling the scope of the ShufflePaws method
...
You can
control the visibility of a class member using a special set of keywords called access modifiers:
Public

Private

82

Defining a property or method of a class as public allows that
property or method to be called from outside the class itself
...
NET pages themselves are objects),
public methods and properties are freely available to the code that
created that instance of the class
...

If a property or method of a class is private, it cannot be used from
outside the class itself
...


Events

Protected

A protected property or method sits somewhere between public
and private
...
We’ll learn more about
derived classes a bit later
...
Of special importance are the class’s public members,
which together form the class’s public interface
...
If, for example, you mark the Sit method
as public, and later decide to make it private, all the other classes that use this
method will have to change accordingly, which is not good
...


Keep Everything Private until you Need It
As a simple guideline for designing your classes, remember that it’s often
easier just to make all the members private, and make public only those that
really need to be public
...


Events
We’ve covered events in some depth already
...
Generally, these changes occur as the result of user interaction with the control
via the browser
...
The object that triggers
the event is referred to as the event sender, while the object that receives the
event is referred to as the event receiver
...


Understanding Inheritance
The term inheritance refers to the ability of a specialized class to refine the
properties and methods exposed by another, more generalized class
...
However, dogs are types of animals, and many characteristics of dogs are shared by all (or most) animals
...
It might be better,
then, for us to create a base class called Animal
...

Similarly, we could create a new class based on the Dog class
...
For instance, we might create
a class called AustralianShepherd, and one for my other dog, Amigo, called
Chihuahua, both of which would inherit the properties and methods of the Dog
base class, and define new classes specific to each breed
...
The best way to appreciate
inheritance is to see it used in a real program
...
NET is in the technique called code-behind, and we’ll build plenty of examples using inheritance and code-behind in Chapter 4
...
NET
If this is the first book in which you’ve read about object oriented programming,
you’ve probably started to dream about objects! Don’t worry, the effect of first
exposure to objects doesn’t usually last for more than a week
...
Moreover,
in the course of this section, we’ll cover some important concepts that every serious
...

So far, we’ve explored various concepts that apply in one form or the other to
almost any truly object oriented language
...

You may already have heard the common mantra of object oriented programmers:
“everything is an object
...
First of all, in C#, every program
consists of a class
...
Yes, objects are everywhere
...
NET extends this to yet another level, giving the phrase “everything is an object”
extra meaning
...
NET, every class ultimately derives from a base
class named Object, so “everything is an object” becomes “everything is an Object
...
NET Page class, you can see the
list of classes from which this class inherits, as shown in Figure 3
...


84

Objects In
...
7
...
This is exactly
the kind of relationship that’s being shown in Figure 3
...
In the same way that we say that an Australian
Shepherd is an Animal, we say that a Page is a Control
...
NET
classes, inherits from Object
...
Object contains the basic functionality
that the designers of
...
The Object
class contains these public members:
❑ Equals
❑ ReferenceEquals
❑ GetHashCode
❑ GetType

85

Chapter 3: VB and C# Programming Basics

❑ ToString
The only member we’re really interested in at this moment is ToString, which
returns the text representation of an object
...
NET is part of the
...
NET Framework Class Library
...
When we want to use certain features
that
...
NET page
...
NET classes in that namespace to achieve
our own ends
...
Data
...
You can view the namespace of a class when visiting its
page in the
...
For example, the Button control’s class can be
found in System
...
UI
...

To use a class that’s part of a namespace that isn’t available to you by default,
you either need to import the namespace, or reference the class using its fully
qualified name, such as System
...
UI
...
To import a namespace
page, we use the Imports directive in VB, and using in C#:
Visual Basic

Imports System
...
SqlClient
C#

using System
...
SqlClient;

86

Using Code-behind Files

As we’ve imported that namespace, we have access to all the classes that it contains
...
Until
now, our ASP
...
NET page
...
Traditional ASP was infamous for creating “spaghetti” code,
which was scattered and intertwined throughout the presentation elements
...
In response to
these problems, ASP
...

This new method, called code-behind, keeps all of your presentational elements
(controls) inside the
...
vb or
...
Consider the following ASP
...
aspx (excerpt)

...
w3
...
dtd">


Sample Page using VB




…user interface elements here…




To access and manipulate a web form programatically, we use the
System
...
UI
...
You might recognize this class from the code-behind

example we saw in Chapter 3
...
In situations in which we’re not using code-behind files (i
...
we write

94

HTML Server Controls

all the code inside the
...

We can use a range of user interface elements inside the form—including typical,
static HTML code—but we can also use elements whose values or properties can
be generated or manipulated on the server either when the page first loads, or
when the form is submitted
...
NET parlance, are
called controls—allow us to reuse common functionality, such as the page header,
a calendar, a shopping cart summary, or a “Today’s Quote” box, for example,
across multiple web forms
...
NET:
❑ HTML server controls
❑ web server controls
❑ web user controls
❑ master pages
There are significant technical differences between these types of controls, but
what makes them similar is the ease with which we can integrate and reuse them
in our web sites
...


HTML Server Controls
HTML server controls are outwardly identical to plain old HTML tags, but include
a runat="server" attribute
...
NET runtime control over the
HTML server controls, allowing us to access them programatically
...

A server-side HTML server control exists for each of HTML’s most common
elements
...
The complete list of current HTML control classes and their
associated tags is given in Table 4
...


95

Chapter 4: Constructing ASP
...
1
...

All the HTML server control classes are contained within the System
...
UI
...
As they’re processed on the server side by the ASP
...
If
you’re familiar with JavaScript, HTML, and CSS, then you’ll know that manipulating text within HTML tags, or even manipulating inline styles within an HTML

96

Using the HTML Server Controls

tag, can be cumbersome and error-prone
...
NET language—for instance, using VB or C#
...
Let’s create
a simple survey form that uses the following HTML server controls:
❑ HtmlForm
❑ HtmlButton
❑ HtmlInputText
❑ HtmlSelect
We’ll begin by creating a new file named Survey
...
Create the file in the
Learning folder you created in Chapter 1
...
aspx (excerpt)

...
w3
...
dtd">


Using ASP<br> ...<br> NET Web Pages<br /><br />Which server technologies do you use?<br /><br /><select id="serverModel" runat="server" multiple="true"><br /><option>ASP<br> ...<br> NET preference options --><br /><p><br />Do you like <br> ...<br> All we’ve done is place some<br />HtmlInputText controls, an HtmlButton control, and an HtmlSelect control inside<br />the obligatory HtmlForm control<br> ...<br> <br /><br />HTML Server Controls in Action<br />Remember, HTML server controls are essentially HTML tags with the runat="server" attribute<br> ...<br> <br /><br />When it’s complete, the Survey<br> ...<br> 1<br> ...<br> 1<br> ...<br> In a real application, we’d probably be more likely to save this information to a database and perhaps show the results as a chart<br> ...<br> aspx (excerpt)<br /><br /><script runat="server" language="VB"><br />Sub Click(ByVal s As Object, ByVal e As EventArgs)<br />Dim i As Integer<br />feedbackLabel<br> ...<br> Value & "<br />"<br />feedbackLabel<br> ...<br> Value & _<br />"<br />"<br />feedbackLabel<br> ...<br> Items<br> ...<br> Items(i)<br> ...<br> Text += " - " & _<br />serverModel<br> ...<br> Text & "<br />"<br />End If<br />Next i<br /><br />99<br /><br /> Chapter 4: Constructing ASP<br> ...<br> Text += "You like <br> ...<br> Value<br />End Sub<br /></script><br />C#<br /><br />File: Survey<br> ...<br> Text = "Your name is: " + name<br> ...<br> Text += "Your email is: " + email<br> ...<br> Text += "You like to work with:<br />";<br />for (int i = 0; i <= serverModel<br> ...<br> Count - 1; i++)<br />{<br />if (serverModel<br> ...<br> Selected)<br />{<br />feedbackLabel<br> ...<br> Items[i]<br> ...<br> Text += "You like <br> ...<br> Value;<br />}<br /></script><br /><br />As with the examples in previous chapters, we start by placing our VB and C#<br />code inside a server-side script block within the <head> part of the page<br> ...<br> Finally,<br />we use the Label control to display the user’s responses within the page<br> ...<br> 2<br> ...<br> <br />Enter some information and click the button<br> ...<br> The<br />information you enter should appear at the bottom of the page when the Confirm<br />button is clicked, as shown in Figure 4<br> ...<br> <br />In conclusion, working with HTML server controls is really simple<br> ...<br> Then,<br />you can simply access and manipulate them using VB or C# code on the server<br />side<br> ...<br> Web server controls are those that generate content for you—you’re no<br />longer in control of the HTML being used<br> ...<br> <br />Let’s look at an example<br> ...<br> To change the Label’s text from within our C# or VB<br />code, we simply set its Text property like so:<br />Visual Basic<br /><br />myLabel<br> ...<br> <br />Again, we can read or set its text using the Text property:<br />C#<br /><br />username = usernameTextBox<br> ...<br> NET still uses an input element<br />behind the scenes; however, we no longer have to worry about this detail<br> ...<br> <br />Unlike HTML server controls, web server controls don't have a direct, one-toone correspondence with the HTML elements they generate<br> ...<br> <br />Web server controls follow the same basic pattern as HTML tags, but the tag<br />name is preceded by asp:, and is capitalized using Pascal Casing<br> ...<br> g<br> ...<br> The<br /><br />101<br /><br /> Chapter 4: Constructing ASP<br> ...<br> g<br> ...<br> <br />Consider the following HTML input element, which creates an input text box:<br /><input type="text" name="usernameTextBox" size="30" /><br /><br />The equivalent web server control is the TextBox control, and it looks like this:<br /><asp:TextBox id="usernameTextBox" runat="server" Columns="30"><br /></asp:TextBox><br /><br />Remember that, unlike any normal HTML that you might use in your web forms,<br />web server controls are first processed by the ASP<br> ...<br> A side effect of this approach is that you must be very<br />careful to always include closing tags (the </asp:TextBox> part above)<br> ...<br> NET is not<br> ...<br> <br />So, you could also write this TextBox like so:<br /><asp:TextBox id="usernameTextBox" runat="server" Columns="30" /><br /><br />To sum up, the key points to remember when working with web server controls<br />are:<br />❑ Web server controls must be placed within a <form runat="server"> tag to<br />function properly<br> ...<br> <br />❑ We include web server controls in a form using the asp: prefix<br> ...<br> We’ll meet many of the web server controls as we<br />work through this and future chapters<br> ...<br> <br /><br />102<br /><br /> Standard Web Server Controls<br /><br />Standard Web Server Controls<br />The standard set of web server controls that comes with ASP<br> ...<br> However, web server controls offer some<br />new refinements and enhancements, such as support for events and view state,<br />a more consistent set of properties and methods, and more built-in functionality<br> ...<br> <br />Remember to use the <br> ...<br> 0 SDK Documentation whenever you<br />need more details about any of the framework’s classes (or controls)<br> ...<br> NET Framework SDK v2<br> ...<br> To find a class, simply search for the class’s name<br> ...<br> For example, you’ll find that<br />there are three classes named Label, situated in the System<br> ...<br> UI<br> ...<br> Web<br> ...<br> WebControls, and System<br> ...<br> Forms namespaces,<br />as Figure 4<br> ...<br> You’ll most likely be interested in the version of the class<br />situated in the WebControls namespace<br> ...<br> 3<br> ...<br> NET Web Pages<br /><br />Label<br />The easiest way to display static text on your page is simply to add the text to<br />the body of the page without enclosing it in any tag<br> ...<br> NET code, you can display your<br />text within a Label control<br> ...<br> Text = "Hello World"<br />End Sub<br />C#<br /><br />public void Page_Load()<br />{<br />messageLabel<br> ...<br> ”<br /><br />Literal<br />This is perhaps the simplest control in ASP<br> ...<br> If you set Literal's Text<br />property, it will simply insert that text into the output HTML code without altering it<br> ...<br> <br /><br />TextBox<br />The TextBox control is used to create a box in which the user can type or read<br />standard text<br> ...<br> The following code shows how we might<br />use it in a simple login page:<br /><br />104<br /><br /> Standard Web Server Controls<br /><br /><p><br />Username: <asp:TextBox id="userTextBox" TextMode="SingleLine"<br />Columns="30" runat="server" /><br /></p><br /><p><br />Password: <asp:TextBox id="passwordTextBox"<br />TextMode="Password" Columns="30" runat="server" /><br /></p><br /><p><br />Comments: <asp:TextBox id="commentsTextBox"<br />TextMode="MultiLine" Columns="30" Rows="10"<br />runat="server" /><br /></p><br /><br />In each of the instances above, the attribute TextMode dictates the kind of text<br />box that’s to be rendered<br> ...<br> We can set its only important property, Value<br> ...<br> When a button is clicked, the form containing the button is<br />submitted to the server for processing, and both the Click and Command events<br />are raised<br> ...<br> When the button is clicked, the<br />Click event is raised and the WriteText subroutine is called<br> ...<br> Text = "Hello World"<br />End Sub<br /><br />105<br /><br /> Chapter 4: Constructing ASP<br> ...<br> Text = "Hello World";<br />}<br /><br />It’s important to realize that events are associated with most web server controls,<br />and the basic techniques involved in using them, are the same events and techniques we used with the Click event of the Button control<br> ...<br> <br /><br />ImageButton<br />An ImageButton control is similar to a Button control, but it uses an image that<br />we supply in place of the typical system button graphic<br> ...<br> gif"<br />runat="server" OnClick="WriteText" /><br /><asp:Label id="messageLabel" runat="server" /><br /><br />The Click event of the ImageButton receives the coordinates of the point at<br />which the image was clicked:<br />Visual Basic<br /><br />Public Sub WriteText(s As Object, e As ImageClickEventArgs)<br />messageLabel<br> ...<br> X & "," & e<br> ...<br> Text = "Coordinate: " + e<br> ...<br> Y;<br />}<br /><br />LinkButton<br />A LinkButton control renders a hyperlink that fires the Click event when it’s<br />clicked<br> ...<br> NET code, LinkButtons can be treated<br />in much the same way as buttons, hence the name<br> ...<br> Unlike the LinkButton control, which offers features<br />such as Click events and validation, HyperLinks are meant to be used to navigate<br />from one page to the next<br> ...<br> sitepoint<br> ...<br> gif" runat="server">SitePoint</asp:HyperLink><br /><br />If it’s specified, the ImageUrl attribute causes the control to display the specified<br />image, in which case the text is demoted to acting as the image’s alternate text<br> ...<br> <br /><asp:CheckBox id="questionCheck" Text="I agree, I like <br> ...<br> The Checked property is<br />True if the checkbox is checked, and False otherwise<br> ...<br> Radio<br />buttons are grouped together using the GroupName property<br> ...<br> <br /><br />107<br /><br /> Chapter 4: Constructing ASP<br> ...<br> <br /><br />Image<br />An Image control creates an image that can be accessed dynamically from code;<br />it equates to the <img> tag in HTML<br> ...<br> gif" runat="server"<br />AlternateText="description" /><br /><br />ImageMap<br />The ImageMap control generates HTML to display images that have certain<br />clickable regions called hot spots<br> ...<br> <br />These areas are defined using three controls that generate hot spots of different<br />shapes: CircleHotSpot, RectangleHotSpot, and PolygonHotSpot<br> ...<br> jpg"><br /><asp:CircleHotSpot AlternateText="Button1"<br />Radius="20" X="50" Y="50" /><br /><asp:CircleHotSpot AlternateText="Button2"<br />Radius="20" X="100" Y="50" /><br /></asp:ImageMap><br /><br />Table 4<br> ...<br> Possible values of HotSpotMode<br />HotSpotMode value<br /><br />Behavior when hot spot is clicked<br /><br />Inactive<br /><br />none<br /><br />Navigate<br /><br />The user is navigated to the specified URL<br> ...<br> <br />When set for an ImageMap, this value is effectively equivalent<br />to Navigate<br> ...<br> <br /><br /> Standard Web Server Controls<br /><br />To configure the action that results when a hot spot is clicked by the user, we<br />set the HotSpotMode property of the ImageMap control, or the HotSpotMode<br />property of the individual hot spot objects, or both, using the values shown in<br />Table 4<br> ...<br> If the HotSpotMode property is set for the ImageMap control as well as<br />for an individual hot spot, the latter property will override that set for the more<br />general ImageMap control<br> ...<br> NET Framework 2<br> ...<br> <br /><br />PlaceHolder<br />The PlaceHolder control lets us add elements at a particular place on a page at<br />any time, dynamically, through our code<br> ...<br> InnerText = "My New Button"<br />placeHolder<br> ...<br> Add(myButton)<br />End Sub<br />C#<br /><br />public void Page_Load()<br />{<br />HtmlButton button myButton = new HtmlButton();<br />myButton<br> ...<br> Controls<br> ...<br> <br />For instance, the Panel could be made visible or hidden by a Button’s Click<br />event:<br /><br />109<br /><br /> Chapter 4: Constructing ASP<br> ...<br> The Button<br />control is outside of the panel<br> ...<br> Visible = False<br />End Sub<br />C#<br /><br />public void HidePanel(Object s, EventArgs e)<br />{<br />myPanel<br> ...<br> <br /><br />List Controls<br />Here, we’ll meet the ASP<br> ...<br> <br /><br />DropDownList<br />A DropDownList control is similar to the HTML select element<br> ...<br> <br /><asp:DropDownList id="ddlFavColor" runat="server"><br /><asp:ListItem Text="Red" value="red" /><br /><asp:ListItem Text="Blue" value="blue" /><br /><br />110<br /><br /> List Controls<br /><br /><asp:ListItem Text="Green" value="green" /><br /></asp:DropDownList><br /><br />The most useful event that this control provides is SelectedIndexChanged<br> ...<br> These controls can also be bound to a database, allowing you to extract<br />dynamic content into a drop-down menu<br> ...<br> If you<br />set the SelectionMode attribute to Multiple, the user will be able to select more<br />than one item from the list, as in this example:<br /><asp:ListBox id="listTechnologies" runat="server"<br />SelectionMode="Multiple"><br /><asp:ListItem Text="ASP<br> ...<br> However, the RadioButtonList control represents a list of radio buttons<br />and uses more compact syntax<br> ...<br> NET Web Pages<br /><br /><asp:ListItem Text="Tacos" Value="tacos" /><br /><asp:ListItem Text="Pasta" Value="pasta" /><br /></asp:CheckBoxList><br /><br />BulletedList<br />The BulletedList control displays bulleted or numbered lists, using <ul> (unordered list) or <ol> (ordered list) tags<br> ...<br> <br />The first property you'll want to set is DisplayMode, which can be Text (the default), or HyperLink, which will render the list items as links<br> ...<br> <br />The other important property is BulletStyle, which determines the style of the<br />bullets<br> ...<br> If the style is set to CustomImage, you’ll<br />also need to set the BulletStyleImageUrl to specify the image to be used for<br />the bullets<br> ...<br> <br /><br />Advanced Controls<br />These controls are advanced in terms of their usage, the HTML code they generate, and the background work they do for you<br> ...<br> NET; we’ll learn more about many of them (as<br />well as others that aren’t covered in this chapter) as we progress through this<br />book<br> ...<br> NET controls<br> ...<br> <br />The Calendar control requires very little customization, and can be created<br />within a page like this:<br /><br />112<br /><br /> Advanced Controls<br /><br />File: Calendar<br> ...<br> 01//EN"<br />"http://www<br> ...<br> org/TR/html4/strict<br> ...<br> 4<br> ...<br> 4<br> ...<br> 3<br> ...<br> NET Web Pages<br /><br />Table 4<br> ...<br> Some of the Calendar control’s properties<br />Property<br /><br />Description<br /><br />DayNameFormat<br /><br />This property sets the format of the day names<br> ...<br> The default is Short, which displays the three-letter<br />abbreviation<br> ...<br> By default, the value of this property<br />is determined by your server’s region settings, but you can<br />set this to Sunday or Monday if you want to control it<br> ...<br> <br /><br />SelectedDate<br /><br />This property contains a DateTime value that specifies the<br />highlighted day<br> ...<br> <br /><br />SelectionMode<br /><br />This property determines whether days, weeks, or months<br />can be selected; its possible values are Day, DayWeek, DayWeekMonth, and None, and the default is Day<br> ...<br> <br /><br />SelectMonthText<br /><br />This property controls the text of the link that’s displayed<br />to allow users to select an entire month from the calendar<br> ...<br> <br /><br />ShowDayHeader<br /><br />If True, this property displays the names of the days of the<br />week<br> ...<br> <br /><br />ShowGridLines<br /><br />If True, this property renders the calendar with grid lines<br> ...<br> <br /><br />ShowNextPrevMonth If True, this property displays next/previous month links<br> ...<br> <br />ShowTitle<br /><br />114<br /><br />If True, this property displays the calendar’s title<br> ...<br> <br /><br /> Advanced Controls<br /><br />Property<br /><br />Description<br /><br />TitleFormat<br /><br />This property determines how the month name appears<br />in the title bar<br> ...<br> <br />The default is MonthYear<br> ...<br> By<br />default, this value is not highlighted within the Calendar<br />control<br> ...<br> <br /><br />Let’s take a look at an example that uses some of these properties, events, and<br />methods to create a Calendar control that allows users to select days, weeks, and<br />months<br> ...<br> aspx, and add a label to it, as follows:<br />File: Calendar<br> ...<br> aspx (excerpt)<br /><br /><script runat="server" language="VB"><br />Sub SelectionChanged(ByVal s As Object, ByVal e As EventArgs)<br />myLabel<br> ...<br> SelectedDates<br />myLabel<br> ...<br> ToString("D") & "<br />"<br />Next<br />End Sub<br /></script><br />C#<br /><br />File: Calendar<br> ...<br> Text = "";<br />foreach (DateTime d in myCalendar<br> ...<br> Text += d<br> ...<br> NET Web Pages<br /><br />}<br />}<br /></script><br /><br />Save your work and test it in a browser<br> ...<br> The<br />selection will be highlighted similar to this display shown in Figure 4<br> ...<br> <br /><br />Figure 4<br> ...<br> Using the Calendar control<br /><br />In SelectionChanged, we loop through each date that the user has selected, and<br />append it to the BulletedList we added to the page<br> ...<br> However, it’s more than a mere substitute<br />for creating a randomization script from scratch<br> ...<br> Also, the XML file allows you<br />to control the banner’s image, link, link target, and frequency of appearance in<br />relation to other banner ads<br> ...<br> As most of the<br />AdRotator control’s properties reside within an XML file, if you wished, you<br />could share that XML file on the Web, essentially allowing value added resellers<br />(VARS), or possibly your companies’ partners, to use your banner advertisements<br />on their web sites<br> ...<br> XML is<br />very easy to start with because of its close resemblance to your old friend<br />HTML: both are largely comprised of tags inside angle brackets (< and >),<br />and any tag may contain attributes specific to that tag<br> ...<br> <br />Take a look at the following HTML element:<br /><p>Star Wars Episode I: The Phantom Menace</p><br />This example describes the content between the tags as a paragraph<br> ...<br> But what if we want to access those<br />words as data?<br />Like HTML, XML’s purpose is to describe the content of a document<br> ...<br> Using XML, the web author can mark up the<br />contents of a document, describing that content in terms of its relevance as<br />data<br> ...<br> NET Web Pages<br /><br /><film><br /><title>Star Wars Episode I: The Phantom Menace

Here, the XML tag names we’ve chosen best describe the contents of the
element
...
For instance,
in the example above, you may decide that you want to differentiate between
the VHS version and the DVD version of the film, or record the name of
the movie’s director
...
xml in your Learning folder,
and insert the content presented below
...

File: Ads
...
gif
http://www
...
com

_blank
Work at Dorknozzle
...
gif
http://www
...
com

_blank
Get the Nozzle Newsletter!
Marketing Sites
1



As you can see, the Advertisements element is the root node, and in accordance
with the XML specification, it appears only once
...
For instance, the above advertisement
file contains details for two banner advertisements
...
xml file enables you to specify properties
for each banner advertisement by inserting appropriate elements inside each of
the Ad elements
...

Impressions

the relative frequency that a particular banner ad should be shown in relation
to other banner advertisements
The higher this number, the more frequently that specific banner will display
in the browser
...

Except for ImageURL, all these elements are optional
...

To make use of this Ads
...
NET page, called AdRotator
...
aspx (excerpt)

...
w3
...
dtd">


AdRotator Control




119

Chapter 4: Constructing ASP
...
xml" />




You’ll need to download workatdorknozzle
...
gif
and place them in the Learning folder in order to see these ad images
...
6
...
6
...
aspx

Refresh the page a few times, and you’ll notice that the first banner appears more
often than the second
...


TreeView
The TreeView control is a very powerful control that’s capable of displaying a
complex hierarchical structure of items
...

The TreeView can pull its data from various sources
...
By default, this sitemap is read from a file called Web
...
The Web
...
sitemap

xmlns="http://schemas
...
com/AspNet/SiteMap-File-1
...
aspx"
description="Home">
description="ClickEvent Example" />
...
w3
...
dtd">


TreeView Demo



runat="server" />
DataSourceID="mySiteMapDataSource" />




121

Chapter 4: Constructing ASP
...
There are many data source controls like this; we’ll
delve into this in more detail later
...
sitemap file above, this web form would
generate an output such as that shown in Figure 4
...


Figure 4
...
A simple TreeView control

As you can see, the TreeView control generated the tree for us
...

In many cases, we don’t want to show the root node; we can hide it from view
by setting the ShowStartingNode property of the SiteMapDataSource to false:
ShowStartingNode="false" />

SiteMapPath
The SiteMapPath control provides the functionality to generate a breadcrumb
navigational structure for your site
...
An example of a
breadcrumb navigation system is shown in Figure 4
...

The SiteMapPath control will automatically use any SiteMapDataSource control
that exists in a web form to display a user's current location within the site
...
8:

122

Advanced Controls

Figure 4
...
A breadcrumb created using the SiteMapPath control

File: TreeViewDemo
...
8
...
aspx, the
root node link won’t show up
...
aspx, the SiteMapPath control won’t generate any output
...

The most important differences between the two lie in their appearances, and
the fact that Menu supports templates for better customization and displays only
two levels of items (menu and submenu items)
...
A MultiView can store more pages
of data (called views), and lets you show one page at a time
...
NET Web Pages

ActiveViewIndex property
...


The contents of each template are defined inside child View elements
...
aspx (excerpt)

...
w3
...
dtd">


MultiView Demo




runat="server" OnClick="SwitchPage" />


ActiveViewIndex="0">


...





...








As you can see, by default, the ActiveViewIndex is 0, so when this code is first
executed, the MultiView will display its first template, shown in Figure 4
...

Clicking on the button will cause the second template to be displayed
...
aspx (excerpt)


C#

File: MultiViewDemo
...
ActiveViewIndex =
(myMultiView
...

The MultiView controls has a number of other handy features, so be sure to
check the documentation for this control if you're using it in a production environment
...
It’s
able to display one or more pages at a time, but also includes additional built-in
functionality such as navigation buttons, and a sidebar that displays the wizard’s
steps
...

You’ll learn how to use this control in Chapter 14
...
NET Web Pages

Web User Controls
As you build real-world projects, you’ll frequently encounter pieces of the user
interface that appear in multiple places—headers or footers, navigation links, and
login boxes are just a few examples
...
NET’s built-in controls
...

Creating customized web server controls makes sense when you need to build
more complex controls that provide a high level of control and performance, or
you want to create controls that can be integrated easily into many projects
...
These are also powerful and reusable within a given
project; they can expose properties, events, and methods, just like other controls;
and they’re easy to implement
...
Web
...
UserControl, and contains the basic functionality that you need

to extend to create your own controls
...
As such, it’s more difficult to distribute them, or include them in other
projects, than it is to distribute or reuse web server controls
...
The file extension of a web user control is
...


Creating a Web User Control
Let’s get a feel for web user controls by stepping through a simple example
...
10
...

Rather than adding many labels and text boxes to the form, and then having to
set all their properties, let’s make life easier by building a web user control that

126

Creating a Web User Control

Figure 4
...
A simple form

includes a Label of the specified width, and a TextBox that accepts 20 characters;
you’ll then be able to reuse the web user control wherever it’s needed in your
project
...
ascx
...
ascx (excerpt)



MaxLength="20" />



Label Widths in Firefox
Unfortunately, setting the Width property of the Label control doesn’t
guarantee that the label will appear at that width in all browsers
...

To get around this, you should use a CSS style sheet and the CssClass
property, which we’ll take a look at later in this chapter
...
So far, you’ve worked with

127

Chapter 4: Constructing ASP
...
For example, you’ve seen a lot of code
that sets the Text property of the Label control
...

Our SmartBox control extends the base System
...
UI
...

❑ Text is a read-only property that returns the text typed by the user in the text
box
...
ascx (excerpt)


C#


C#

File: ControlTest
...
LabelText = "Name:";
addressSb
...
LabelText = "Country:";
phoneSb
...
NET 2
...
Master pages are similar to web
user controls in that they are also composed of HTML and other controls; they
can be extended with the addition of events, methods, or properties; and they
can’t be loaded directly by users—instead, they’re used as building blocks to
design the structure of your web forms
...
For example, a master page can set out a standard structure

132

Master Pages

containing the header, footer, and other elements that you expect to display in
multiple web forms within a web application
...
master extension, and, just like web forms and web
user controls, they support code-behind files
...
Web
...
MasterPage
...
If your site uses these features in a
well-planned way, it can be very easy to modify certain details in the layout or
functionality of your site, because updating a master page or a web user control
has immediate effects on all the web forms that use the file
...
As its name suggests, the
ContentPlaceHolder is a placeholder that can be filled with content relevant to
the needs of each web form that uses the master page
...

Let’s see how this works with a simple example
...
11
...
11
...
NET Web Pages

If all the pages in the site have the same header, footer, and navigation menu, it
makes sense to include these components in a master page, and to build several
web forms that customize only the content areas on each page
...

To keep this example simple, we won’t include a menu here: we'll include just
the header, the footer, and the content placeholder
...
master, and write the following code into
it:
File: FrontPages
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
If you want to build a web form
based on this master page, you just need to reference the master page using the
Page directive in the web form, and add a Content control that includes the
content you want to insert
...
Create a web form called FrontPage
...
aspx (excerpt)

<%@ Page MasterPageFile="FrontPages
...




134

Using Cascading Style Sheets (CSS)

You’re all set now! Loading FrontPage
...
12
...
12
...
In our case, the master page
contains a single ContentPlaceHolder, but it could have more
...


Using Cascading Style Sheets (CSS)
It’s clear that controls make it easy for us to reuse pieces of functionality in
multiple places
...

However, controls don’t solve the problem of defining and managing the visual
elements of your web site
...
The process is even more painful if the client
wants a more serious update, like rearranging components on the pages
...
NET offer you
...
HTML was initially designed to deliver simple text content, and paid

135

Chapter 4: Constructing ASP
...

HTML left it to the individual browsers to work out these intricacies, and tailor
the output to the limitations and strengths of users’ machines
...

CSS gives web developers the power to create one set of styles in a single location,
and to apply those styles to all of the pages in our web site
...
Regardless of whether our site contains three pages or 300,
when we alter the styles in the style sheet, our changes are immediately applied
to all pages that use the style sheet
...
NET 2
...
You’ll learn more
about these features in Chapter 5
...
This makes
updating a web site’s overall look a cakewalk
...
css" />

In the above example, file
...



The problem with using these “embedded” styles is that we can’t reuse those
styles in another page without having to type them in again, which makes
global changes to the site very difficult to manage
...
For instance, we might give a paragraph a border, and color it red, with
the following markup:


Copyright 2006



When used in embedded or external style sheets, the first part of any style rule
must determine the elements to which the rule will apply; we do this using a selector
...
NET, we typically use two types of selectors:
element type selectors
An element type selector targets every single instance of the specified element
...
For example, the following markup shows a paragraph whose class
attribute is set to fineprint:

137

Chapter 4: Constructing ASP
...
fineprint
{
font-family: Arial;
font-size: x-small;
}

Whether you’re building external style sheets, embedded style sheets, or inline
style rules, style declarations use the same syntax
...
NET applications
...
Here’s a
list of the most common property types:
font
This category provides you with the ability to format text level elements, including their font faces, sizes, decorations, weights, colors, etc
...

These values give you control over the background, including whether you’d
like to use a color or an image for the background, and whether or not you
want to repeat a background image
...


138

Types of Styles and Style Sheets

box
The box category allows us to customize tables
...

border
This category lets you draw boxes of different colors, styles, and thicknesses
around page elements
...

positioning
Modifying positioning allows you to move and position tags and controls
freely
...
As we progress through the book, the many types of style
properties will become evident
...
You can
associate classes with ASP
...

In most cases, the value you give the CssClass property will be used as the value
of the resulting element’s class attribute
...
First, create in your Learning folder a file named
Styles
...
css


...
dropdownmenu
{
font-family: Arial;
background-color: #0099FF;
}

139

Chapter 4: Constructing ASP
...
textbox
{
font-family: Arial;
background-color: #0099FF;
border: 1px solid
}

...
aspx with this code:
File: UsingStyles
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
css" type="text/css" rel="stylesheet" />



Please select a product:



CssClass="dropdownmenu" runat="server">







runat="server" />



Text="Add To Cart" runat="server" />






140

Summary

Loading this page should produce the output shown in Figure 4
...


Figure 4
...
CSS at work

In the next chapter, we’ll learn to use Visual Web Developer to create CSS
definitions through a simple visual interface
...
All these elements can be combined to create powerful structures for your web sites
...


141

142

5

Building Web Applications

In the previous chapters, we discussed the different pieces of ASP
...
In this chapter, you’ll put together everything you’ve learned so far as we
place this new knowledge in context
...
The tool we recommend you use as you learn to build ASP
...
You learned how to install this tool in Chapter 1, and in this
chapter, we’ll teach you how to use it to its full potential
...
NET web applications: any old text
editor will do
...


Using Visual Studio
If you have access to Microsoft’s commercial Visual Studio program, you
could make use of that instead of Visual Web Developer
...
Visual Studio has a lot more features than

Chapter 5: Building Web Applications

Visual Web Developer, and a few of the tools are named differently to reflect
this
...
For the purposes of this book,
these tools are equivalent, and you should feel free to use Visual Studio if
you have access to it
...
Along
the way, we’ll also explore many interesting ASP
...

❑ We’ll work with Web
...
asax, and the special ASP
...

❑ We’ll use the application state, user sessions, the application cache, and
cookies
...


Introducing the Dorknozzle Project
While most books give you a series of simple, isolated examples to illustrate
particular techniques, this book is a little different
...
We’ll build on this application as we
move through the remaining chapters of this book—the Dorknozzle intranet will
give us a chance to investigate and grasp the many different concepts that are
important to developers of any type of web application
...
We’ll assume that the pages in the Dorknozzle intranet will
be laid out as shown in Figure 5
...

The menu on the left suggests that the site will have more pages than this
homepage, and that they’ll have the same structure: on every page of the site,
the menu will sit on the left, and the header will be identical to the one shown
here
...

(If you paid attention in Chapter 4, you’ll already have realized that this is a
scenario where it makes sense to use master pages
...
1
...


help desk

This page allows Dorknozzle employees to submit
problems they experience with software, hardware, or
their computers, as help desk tickets that are sent to
an IT administrator
...


address book

While the employee directory houses handy information for staff use, the purpose of the address book is
to provide more detailed information about every employee within the company
...


145

Chapter 5: Building Web Applications

admin tools

Administrators will need the ability to perform various
administrative tasks, such as updating users’ information
...


admin newsletter

This page will allow administrators to send email
newsletters to the company employees
...
However, before
you can begin to create all these smaller applications, we’ll need to build the
framework that will act as a template for the site as a whole
...


Figure 5
...
Using Visual Web Developer

146

Using Visual Web Developer

Using Visual Web Developer
The first step in learning how to use this tool is, obviously, starting it up
...
You’ll
be welcomed by a page that looks something like the one shown in Figure 5
...

Let’s start by creating a new web site
...

In the dialog that appears, which is shown in Figure 5
...
NET Web
Site template, choose the web site’s default language, and identify the location
at which the web site should be created
...
For the location, create a folder named Dorknozzle
located in the WebDocs folder you’ve been working with so far
...
If you placed WebDocs in
the root folder of C:\, the location will be C:\WebDocs\Dorknozzle
...
3
...
When
you’re working with a web site project that’s saved to the file system, Visual
Web Developer’s web server is used to execute the project
...

In that case, you’d need to specify an HTTP location, such as http://localhost/Dorknozzle
...
We’ll take
a look at IIS (or Cassini) a bit later
...
It should look something like the one shown in Figure 5
...


Figure 5
...
Your new Dorknozzle web application

148

Meeting the Features

Don’t be daunted by the many forms and windows around your screen—each
has something to offer! Visual Web Developer is very flexible, so you can resize,
relocate, or regroup the interface elements that appear
...


The Solution Explorer
The Solution Explorer, which by default is located in the upper right-hand part
of the Visual Web Developer window, provides the main view of your project,
and displays the files of which your project is composed
...
5 shows,
the root node is the location of your project; beneath the root node you can see
that Visual Web Developer has already created other elements for you
...
5
...
If you’re using C#,
Web
...
Don’t worry—we’ll create this file later
...
5:
❑ App_Data is a special folder that ASP
...
You’ll
learn more about this folder in Chapter 13
...
aspx is the default web form that Visual Web Developer creates for
you
...
aspx
node by clicking the + sign to its left
...
aspx
...
aspx
...
Visual Web Developer can work with web forms that use a code-behind file, as well as with
those that don’t
...
config is your web application’s configuration file
...
config,
you can set numerous predefined configuration options for your project (for
instance, you can enable debug mode)
...
We’ll come back to this
file later in the chapter
...
If you right-click on each node,
a list of options that are specific to that particular node type will appear
...
Double-click on a file, and that file will open in an appropriate
editor (for instance, double-clicking on a web form will open that file in the Web
Forms Designer)
...
The Web Forms Designer is a very powerful
tool that allows you to edit web forms, web user controls, and master pages
...

By default, when you start a new web site project, the Web Forms Designer will
display the contents of Default
...
6
...
In Figure 5
...
aspx, and the Start Page (the window
that was initially loaded when Visual Web Developer started) are open
...
6
...
Since there’s no content in the page as yet, you’ll see an
empty window, but you can populate it by typing text, or dragging controls from
the Toolbox (which we’ll discuss in a moment) onto the page
...
7, I’ve
typed Hello World! into the Design View
...
If you’ve

150

Meeting the Features

Figure 5
...
Viewing Default
...
7
...


The Code Editor
As well as editing web forms, web developers commonly edit those forms’ codebehind files
...


151

Chapter 5: Building Web Applications

If you’ve opened a web form in the Web Forms Designer, you can easily switch
to its code-behind file: click the View Code icon in the Solution Explorer, rightclick the Web Form in Solution Explorer, and select View Code; alternatively,
expand the Web Form’s node in Solution Explorer and double-click its code-behind file
...
aspx
...
aspx
...
8
...
8
...
aspx
...
9
...
aspx
...
9
...
But,
for the VB template, Visual Web Developer adds these references to the
Web
...
This explains why
a Web
...
In the end, the functionality is very similar, but the Visual Web Developer
designers chose to implement this functionality differently for each language
...
config yourself if
you’re using C#
...
In Figure 5
...
aspx
...
If you hover your
cursor over the ellipsis, you’ll see a preview of the hidden text
...
10
...
In its latest incarnation as part of Visual
Web Developer 2005 Express Edition, IntelliSense is pretty close to perfection
...


153

Chapter 5: Building Web Applications

Let’s do a quick test
...
Web
...
Page line in Default
...
vb
...
11 shows,

IntelliSense will automatically display other words that could be used in that
position
...
11
...
For example, if you’re using C#, IntelliSense isn’t triggered as frequently
as it is for those using VB
...
Then, once you’ve selected the correct entry, press Tab or Enter to
have the word completed for you
...
The Toolbox contains most of the popular ASP
...

You must be viewing a form in the Web Forms Designer to see the proper controls
in the Toolbox
...
12, select
View > Toolbox to make it appear
...

The controls listed in the Toolbox are grouped within tabs that can be expanded
and collapsed
...
12
...
In the other tabs, you’ll find other
controls, including the validation controls we’ll discuss in Chapter 6, which can
be found in the Validation tab
...
13 shows the toolbox with all its tabs in
the collapsed state
...
13
...
For example, if you select the TextBox
control we added to the form earlier, the properties of that TextBox will display
in the Properties window
...

The Properties window doesn’t just allow you to see the properties—it also lets
you set them
...
In Figure 5
...


Figure 5
...
Setting a color using the Properties window

By default, the control’s properties are listed by category, but you can order them
alphabetically by clicking the A-Z button
...


Executing your Project
You already know from our work back in Chapter 1 that, in order to execute an
ASP
...
Unfortunately, users of Windows XP Home Edition can’t use IIS, so until now,
you’ve most likely been using Cassini, a lightweight web server that Microsoft
has made available for development purposes
...
We’ll also see
how you can use Visual Web Developer to execute your project through IIS
...
NET web sites even on machines whose operating
systems don’t have IIS—Windows XP Home Edition, for example
...
aspx file we
first saw back in Chapter 2, only this time we’ll name it Default
...

Visual Basic

File: Default
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
Text = "Hello, World!"
End Sub








C#

File: Default
...
0 Strict//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-strict
...
Text = "Hello, World!";
}





157

Chapter 5: Building Web Applications






You can start the web server by executing the project: select Debug > Start Without
Debugging, or use the keyboard shortcut Ctrl-F5
...
aspx in your system’s default web browser, as shown in Figure 5
...


Figure 5
...
Executing a page using Visual Web Developer

We executed this project without debugging it, but generally you’ll want to run
projects with debugging enabled (using F5, or Debug > Start Debugging)
...

To enable debugging, you must modify an option in a file called Web
...
We’ll take a more in-depth
look at Web
...
For now, all you need to know is that the first time
you try to debug the project, Visual Web Developer will ask you whether you
want to enable debugging in Web
...
16
...

Once you click OK, the application will execute
...
15, but this time you have more
control over your application, as we’ll soon see
...
When you execute a project using the
integrated web server, it will run on a random port, and the complete URL location
will reflect the physical path
...
15, you can see that the integrated web
server was running on port 1855, which explains the complete URL: http://loc-

158

Using Visual Web Developer’s Built-in Web Server

Figure 5
...
Enabling Debug Mode in Visual Web Developer

alhost:1855/Dorknozzle/Default
...
IIS usually runs on the default port,
which explains why it doesn’t need to be mentioned explicitly
...
If you run multiple projects at the
same time, more web servers will be created and more icons will appear
...
17
...
17
...
For the purpose
of running and debugging your ASP
...
For example, if you close
the Internet Explorer window while your project runs in debug mode, Visual Web

159

Chapter 5: Building Web Applications

Developer will stop the application automatically
...
18
...
18
...
Then, right-click the root node in
Solution Explorer, and select Browse With to display the dialog shown in Figure 5
...
Select Internet Explorer, click Set as Default, and click Browse
...
19
...
Although Microsoft recommends that we stick with Visual Web Developer for learning purposes, it’s very
easy to use IIS
...

To run your web application using IIS, you’ll need to create an IIS virtual directory
and make it point to the project’s physical folder on the disk
...

Start by opening the Internet Services Manager by selecting Start > All Programs
> Administrative Tools > Internet Information Services
...
20
...
20
...
Choose Dorknozzle
...
Leave all the other settings to their
defaults
...

Let’s spend some time learning about your new virtual directory
...
A dialog
like the one shown in Figure 5
...


161

Chapter 5: Building Web Applications

Figure 5
...
Editing the virtual directory’s properties

The Virtual Directory tab shows the basic settings of your virtual directory
...
When a virtual directory is set as an
IIS application, IIS takes special care of that location by isolating all of that directory’s pages and subdirectories into what’s called an application domain
...
So even if we built an intranet web application for a company’s staff,
then placed a separate application for external users on the same web server,
code would never cross-reference or conflict between those two applications
...


162

Using IIS

application level security policies
You can set different permissions for the different applications on the server
...
We’ll discuss this in detail in Chapter 13
...
asax and Web
...

The Global
...
config file specifies configuration settings for
the application
...
NET web
application can contain a number of special folders, such as App_Themes,
App_Code or App_Data
...


Applications and Visual Web Developer’s Web Server
When you use Visual Web Developer’s integrated web server to run your
project, the virtual directory it creates for you on the spot is also set as an
application, so it, too, enjoys all the benefits mentioned above
...
If you click the
Remove button that appears next to the application name, be aware that the action
won’t remove the virtual directory itself: it will remove that application’s IIS application properties
...


163

Chapter 5: Building Web Applications

Figure 5
...
Adding a default name for the document

While you’re here, it’s a good idea to check that Default
...
If it is, then requesting http://localhost/Dorknozzle will load
http://localhost/Dorknozzle/Default
...
To check this, click
the Documents tab
...
aspx isn’t in the list, add it by clicking the Add…
button and entering the filename, as shown in Figure 5
...

Finally, click OK to close the Dorknozzle Properties window
...
21 is
enabled
...

Now, if you load http://localhost/Dorknozzle/ using any web browser, you
should see a little magic (as Figure 5
...
23
...
15, but
this time, the URL shows that it has loaded through the default web server, which,
in this case, is IIS
...
First, select File > Close Project in Visual Web Developer to close
the current project
...
If the project is currently running in debug mode, you’ll also be asked to
confirm that you want to stop debugging
...
24
...
24
...
This time, the root entry in Solution Explorer will be http://localhost/Dorknozzle/ instead of c:\WebDocs\Dorknozzle\, as Figure 5
...


Figure 5
...
Solution Explorer displaying an HTTP location

Visual Web Developer knows how to investigate your IIS location and display
its contents automatically in the Solution Explorer
...


Core Web Application Features
Let’s continue our exploration of the key topics related to developing ASP
...
We’ll put them into practice as we move through the book,
but in this quick introduction, we’ll discuss:
❑ Web
...
asax
❑ user sessions
❑ caching
❑ cookies

Web
...
NET web application contains a file named Web
...
By default, all ASP
...
config

configured in the Machine
...
NET\Framework\version\CONFIG directory
...
However,
you can override certain settings of the Machine
...
config file to the root directory of your application
...

The Web
...
One of the most useful settings that
Web
...
NET’s debug mode
...
config and editing the compilation element,
which looks like this:
File: Web
...
Because this
affects performance, set this value to true only
during development
...

Set explicit="true" to force declaration of all variables
...
The other attributes listed here were added by Visual Web Developer
to offer a helping hand to VB developers migrating from older versions
...

If you’re using C#, you’ll need to create the Web
...
Go to File
> New File…, then select Web Configuration File from the dialog that appears,
and click Add
...
config file, which will contain
the following section:
File: Web
...
Because this
affects performance, set this value to true only
during development
...
NET’s debugging features
...
config can also be used to store custom information for your application

in a central location that’s accessible from all the pages of your site
...
config (excerpt)












168

Web
...
Web
...
WebControls"/>

C#

Application["SiteName"] = "Dorknozzle Intranet Application";

With SiteName set, any pages in the application can read this string:
Visual Basic

Dim appName As String = Application("SiteName")
C#

String appName

= Application["SiteName"];

We can remove an object from application state using the Remove method, like
so:
Visual Basic

Application
...
Remove("SiteName");

If you find you have multiple objects and application variables lingering in application state, you can remove them all at once using the RemoveAll method:
Visual Basic

Application
...
RemoveAll();

It’s important to be cautious when using application variables
...
If you continue to save objects
into the application state without removing them, you can place a heavy demand
on server resources and dramatically decrease the performance of your applications
...
Application state is very commonly
used to maintain hit counters, so our first task in this example will be to build
one! Let’s modify the Default
...
Double-click Default
...
You could drag the control from the Toolbox (in either
Design View or Source View) and modify the generated code, or you could simply
enter the new code by hand
...
aspx (excerpt)



The page has been requested

times!



In Design View, you should see your label appear inside the text, as shown in
Figure 5
...

Now, let’s modify the code-behind file to use an application variable that will
keep track of the number of hits our page receives
...


174

Using Application State

Figure 5
...
The new label appearing in Design View

Visual Basic

File: Default
...
vb (excerpt)

Partial Class _Default
Inherits System
...
UI
...
EventArgs) Handles Me
...
aspx
...
Web
...
Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}

Now, let’s modify the automatically generated method by adding the code that
we want to run every time the page is loaded
...
aspx
...
EventArgs) Handles Me
...
Remove("PageCounter")
End If
' Initialize or increment page counter each time the page loads
If Application("PageCounter") Is Nothing Then
Application("PageCounter") = 1
Else
Application("PageCounter") += 1

175

Chapter 5: Building Web Applications

End If
' Display page counter
myLabel
...
aspx
...
Remove("PageCounter");
}
// Initialize or increment page counter each time the page loads
if (Application["PageCounter"] == null)
{
Application["PageCounter"] = 1;
}
else
{
Application["PageCounter"] =
(int)Application["PageCounter"] + 1;
}
// Display page counter
myLabel
...
ToString(Application["PageCounter"]);
}

Before analyzing the code, press F5 to run the site and ensure that everything
works properly
...
Now, shut down your browser
altogether, and open the page in another browser
...
28 shows
...
First, though, the
code verifies that the counter hasn’t reached or exceeded ten requests
...
Remove("PageCounter")
End If

176

File: Default
...
vb (excerpt)

Using Application State

Figure 5
...
Using the Application object

C#

File: Default
...
cs (excerpt)

// Reset counter when it reaches 10
if (Application["PageCounter"] != null &&
(int)Application["PageCounter"] >= 10)
{
Application
...
You may
remember from Chapter 3 that C# is more strict than VB when it comes to
variable types
...
This conversion won’t work if PageCounter hasn’t been added to application state, so we
also need to check that it’s not equal to null
...
First of all, we need verify that the
counter variable exists in the application state
...
To verify that an element exists in VB, we use
Is Nothing:
Visual Basic

File: Default
...
vb (excerpt)

' Initialize or increment page counter each time the page loads
If Application("PageCounter") Is Nothing Then
Application("PageCounter") = 1
Else
Application("PageCounter") += 1
End If

As we’ve already seen, we compare the value to null in C#:

177

Chapter 5: Building Web Applications

C#

File: Default
...
cs (excerpt)

// Initialize or increment page counter each time the page loads
if (Application["PageCounter"] == null)
{
Application["PageCounter"] = 1;
}
else
{
Application["PageCounter"] =
(int)Application["PageCounter"] + 1;
}

The last piece of code simply displays the hit counter value in the label
...
The
reason for this has to do with the code that increments the counter:
C#

File: Default
...
cs (excerpt)

Application["PageCounter"] =
(int)Application["PageCounter"] + 1;

The expression to the right of the = operator is evaluated first; to do this, the
server must read the value of the PageCounter value stored in the application
...

Now, let’s imagine that two users visit this page at the same time, and that the
web server processes the first user’s request a fraction of a second before the
other request
...
However, before the web form had a chance to store this new value
into application state, another copy of the web form, running for the second user,
might read PageCounter and also obtain the value 6
...
29
...
This process is depicted in Figure 5
...


178

Using Application State

Figure 5
...
Two users updating application state simultaneously

Figure 5
...
Two users updating application state with locks

179

Chapter 5: Building Web Applications

Let’s modify our code slightly to create these locks:
Visual Basic

File: Default
...
vb (excerpt)

' Initialize or increment page counter
If Application("PageCounter") Is Nothing Then
Application("PageCounter") = 1
Else
' Lock the Application object
Application
...
UnLock()
End If
C#

File: Default
...
cs (excerpt)

// Initialize or increment page counter each time the page loads
if (Application["PageCounter"] == null)
{
Application["PageCounter"] = 1;
}
else
{
// Lock the Application object
Application
...
UnLock();
}

In this case, the Lock method guarantees that only one user can work with the
application variable at any time
...
Our use of Lock and UnLock in this
scenario guarantees that the application variable is incremented by one for each
visit that’s made to the page
...
However, unlike application state, which
is accessible to all users, each object stored in session state is associated with a
particular user’s visit to your site
...

The process of reading and writing data into session state is very similar to the
way we read and write data to the application state: instead of using the
Application object, we use the Session object
...

To test session state, you could simply edit the Page_Load method to use Session
instead of Application, and remove the Lock and UnLock calls if you added
them
...

In the page hit counter example that we created earlier in this chapter, we stored
the count in the application state, which created a single hit count that was shared
by all users of the site
...

Like objects stored in application state, session state objects linger on the server
even after the user leaves the page that created them
...

Since web browsers don’t notify web servers when a user leaves a web site,
ASP
...
By default, a user’s session
will expire after 20 minutes of inactivity
...
Timeout = 1560

You can do this anywhere in your code, but the most common place to set the
Timeout property is in the Global
...
If you open Global
...
This method runs

before the first request from each user’s visit to your site is processed, and gives
you the opportunity to initialize their session variables before the code in your
web form has a chance to access them
...
asax (excerpt)

Sub Session_Start(sender As Object, e As EventArgs)
Session
...
asax (excerpt)

void Session_Start(Object sender, EventArgs e)
{
Session
...
Although
there’s nothing to prevent you from doing the same thing here, ASP
...
Cache is also a collection, and
we access its contents similarly to the way we accessed the contents of
Application
...

Let’s assume that there’s a list of employees that you’d normally read from the
database
...
The Cache object also lets us control expiration—if, for example, we want to add an object to the cache for a period of ten
minutes, we can use the Insert method
...
Insert("Employees", employeesTable, Nothing,
DateTime
...
FromMinutes(10))
C#

Cache
...
MaxValue, TimeSpan
...
We could use such dependencies to invalidate cached items

182

Using Cookies

when some external indicator changes, but that kind of task is a little beyond the
scope of this discussion
...

If not, it means that this is the first time the code has been executed, or that the
item has been removed from the cache
...
The
trip to the database server is made only if the cache is empty or not present
...

To store user data for longer periods of time, you need to use cookies
...
NET application can save on the user’s browser,
to be read later by your application
...

In ASP
...
We read the user’s
cookies through the Cookies property of the Request object, and we set cookies
though the Cookies property of the Response object
...

Let’s do a quick test
...
aspx and remove the text surrounding
myLabel:
File: Default
...
aspx
...
EventArgs) Handles Me
...
Cookies("UserID")
' Verify if the cookie exists
If userCookie Is Nothing Then
' Display message
myLabel
...
"
' Create cookie
userCookie = New HttpCookie("UserID", "JoeBlack")
' Set cookie to expire in one month
userCookie
...
Now
...
Cookies
...
Text = "Welcome back, " & userCookie
...
aspx
...
Cookies["UserID"];
// Verify if the cookie exists
if (userCookie == null)
{
// Display message
myLabel
...
";
// Create cookie
userCookie = new HttpCookie("UserID", "JoeBlack");
// Set cookie to expire in one month
userCookie
...
Now
...
Cookies
...
Text = "Welcome back, " + userCookie
...
31
...
31
...
32
...
32 shows
...

What’s interesting to observe is that you can close the browser window, or even
restart your computer—the cookie will still be there, and the application will be
able to identify that you’re a returning visitor
...

Be aware that visitors can choose to reject your cookies, so you can’t rely on them
for essential features of your application
...
Now, it’s time to add some real functionality to it! In the next few pages,
we will:
❑ Prepare the sitemap for your site
...

❑ Create a master page that will contain the layout for all the pages of
Dorknozzle
...

❑ Learn how to debug your project in case you encounter errors
...


Preparing the Sitemap
As we saw in Figure 5
...
We’ll implement that list using
the SiteMapPath control, which will require a sitemap file
...
You can do this by closing the browser window
(if you’re using Internet Explorer), by selecting Debug > Stop Debugging,
or by clicking the Stop icon on the debug toolbar
...
33
...
33
...
34
...
34 and leave
the filename as Web
...

Click Add to have the file created and added to your project
...
Change its contents
as shown below
...

File: Web
...
0" encoding="utf-8" ?>
xmlns="http://schemas
...
com/AspNet/SiteMap-File-1
...
aspx" title="Home"
description="Dorknozzle Home" />
title="Employee Directory"
description="Dorknozzle Employee Directory" />
description="Dorknozzle Departments" />
title="Admin Newsletter"
description="Dorknozzle Admin Newsletter" />



Great! Your sitemap file is ready to be used
...
CSS provides
developers with flexibility and control over the look of their web applications,
and makes it very simple to keep the appearance of the web site consistent
...
NET, style sheets can be managed through a mechanism called themes
...
But first up, let’s add a style sheet
to our Dorknozzle site
...
NET Folder >
Theme
...
Type Blue, then
hit Return
...
35 illustrates
...
35
...


Creating a New Style Sheet
We’ll start by adding a new CSS file to the Blue theme
...
Any files with the

...

Right-click the Blue folder, and select Add New Item…
...
css, and click Add
...
css will be almost empty:
File: Dorknozzle
...
We’ll use these styles
soon, when we build the first page of Dorknozzle
...
css (excerpt)

body
{
font-family: Tahoma, Helvetica, Arial, sans-serif;
font-size: 12px;
}
h1
{
font-size: 25px;
}
a:link, a:visited
{
text-decoration: none;
color: Blue;
}
a:hover
{
color: Red;
}

...
gif);
background-repeat: repeat-x;
}

...
Content
{
top: 160px;
left: 170px;
position: absolute;
width: 600px
}

Remember, we’re not limited to using these styles
...
css file and add them as necessary
...
Right-click on any
style rule in the CSS code editor, and in the context menu that appears (which
is shown in Figure 5
...


Figure 5
...
Choosing to edit a style visually

191

Chapter 5: Building Web Applications

Figure 5
...
Using the Style Builder

If you choose Build Style…, you’ll access the very useful Style Builder tool, shown
in Figure 5
...


Styling Web Server Controls
CSS styles can apply only to HTML elements—they can’t really be used to keep
the appearance of web server controls consistent
...
NET controls, and you saw that some of them contain properties that
affect their output
...
Say you use many calendars throughout
your web site, and all of them are supposed to have the same properties as this
one:
FirstDayOfWeek="Sunday" NextPrevFormat="FullMonth"
SelectionMode="DayWeekMonth" SelectWeekText="Select Week"
SelectMonthText="Select Month" TitleFormat="Month"
OnSelectionChanged="SelectionChanged" />

192

Using Themes, Skins, and Styles

Now, given that you have many calendars, you decide that you’d like to have the
common set of properties saved in a central place
...

So, can CSS help us keep our calendars consistent in the same way it can keep
our headings consistent? Unfortunately, it can’t
...
CSS can affect the final output by setting
the colors or other details of the resulting HTML code, but it can’t influence the
way the Calendar control works on the server
...
NET 2
...
They
define default values for server-side controls
...
skin extension
...
This makes sense, since the skin isn’t an
actual control
...
These
values can be overridden for any specific calendar, but the skin provides the default
values
...
A named skin doesn’t apply automatically to all controls of its type: it affects
only those that specify that the skin applies to them
...


Adding a Skin
The truth is, we don’t really need skins for our simple site, but we’ll add one so
that you can get a feel for their functionality
...
Choose the Skin File template,
leave its name as SkinFile
...


193

Chapter 5: Building Web Applications

Visual Web Developer adds a comment to the file; this comment contains default
text that briefly describes skins
...
ASP
...
skin extension
...
Without skins, we’d need to set this property manually on all TextBox
controls in your site
...
skin file:
File: SkinFile
...


Applying the Theme
In order for your CSS—and the skin—to take effect, you’ll need to apply the
theme to your web page
...
You can apply a new theme using the Web
...

For now we’ll use Web
...
The theme can be set using the theme attribute
of the pages element, which should be located inside the system
...

If you’re using VB, the pages element already exists in Web
...
config (excerpt)












194

Building the Master Page




If you’re using C#, you’ll need to add the pages element to the system
...
config (excerpt)

...
web>

Building the Master Page
This is where the real fun begins! All of the pages in Dorknozzle have a common
structure, with the same header on the top, and the same menu on the left, so it
makes sense to build a master page
...


Figure 5
...
Creating a new master page

Right-click again on the root node in Solution Explorer and select Add New Item…
...
master
...
38
...

After you click the Add button, Visual Web Developer creates the new master
page, which will appear immediately in Solution Explorer
...
39, you’ll see its code-behind file listed as a child node
...
39
...
master file (not its code-behind file) in Solution
Explorer, and you’ll find that Visual Web Developer has given you a very simple
default master page
...
master (excerpt)





ImageUrl="~/Images/header
...
gif" alt="+"
width="16" height="16" style="border-width: 0;" />
<%# Eval("Text") %>


196

Building the Master Page





runat="server" />




The code is pretty simple: basically, it defines the layout of all the Dorknozzle
pages
...
These
elements are positioned on the page using the CSS styles you added earlier to
the Dorknozzle
...

We saw in Chapter 4 that the TreeView and Menu controls know how to read
data from a SiteMapDataSource class, which reads the Web
...
To build the menu on
the left-hand side of the page, we create a Web
...
master (excerpt)

ShowStartingNode="false" />

You might recall that the Web
...

To have the Menu control simply display the list of nodes, it’s sufficient to set its
DataSourceID to the ID of the SiteMapDataSource
...
Here, we used the StaticItemTemplate to add a little book image
to the left of each menu item:
File: Dorknozzle
...
gif" alt="+"
width="16" height="16" style="border-width: 0;" />
<%# Eval("Text") %>

197

Chapter 5: Building Web Applications




After you write Dorknozzle
...
1
Once this is done, you should have a Dorknozzle\Images folder that contains a
few image files
...

The master page is now in place
...
Does yours look like the page shown in
Figure 5
...
40
...
master in Design View

Note that the CSS styles don’t apply at design time, so you’ll have to hang on a
little longer to see that code in action
...
com
...
aspx web
form, but this time, we’ll use the master page
...
aspx file by right-clicking that file in Solution Explorer, and choosing
Delete
...
aspx is about to be deleted (see Figure 5
...


Figure 5
...
Deleting Default
...

In the dialog that appears, choose the Web Form template, leave the default name
of Default
...
42
...
42
...
aspx

199

Chapter 5: Building Web Applications

Once you click Add, you’ll be asked to select the master page you want to use
...
master, and click OK
...
aspx (excerpt)

<%@ Page Language="VB" MasterPageFile="~/Dorknozzle
...
aspx
...
Let’s modify the file by adding some content to the ContentPlaceHolder,
and altering the page title
...
aspx (excerpt)

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


Company Events


We'll add company events later
...
43
...

By default, when you select Debug > Start Debugging or press F5, Visual Web
Developer executes the page that’s being edited
...
To make sure that
Default
...
aspx in Solution Explorer, and select Set As Start Page
...
aspx by hitting F5
...
44, with all the CSS applied
...
43
...
44
...
This form will allow our fictitious employees to report hardware, software,

201

Chapter 5: Building Web Applications

and workstation problems to the help desk
...
The process
will include the following stages:
❑ Choose from a predefined list of potential problem areas
...

❑ Enter a description of the problem
...

As we already have a master page that defines the layout of the site’s pages, adding
a new page to the site is now a trivial task
...
NET web site once the structure has been created
correctly
...
aspx, but this time,
name it HelpDesk
...
Be sure to check both the Place code in separate file
and Select master page checkboxes
...
aspx (excerpt)

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

When you’re finished, save your work, execute the project, and click the Help
Desk link from the menu
...
45
...
45
...
If you
type text into the text boxes, you’ll see that the color of the text is blue
...
As such, it’s important that you know how to
use them
...
A constant truth in the
life of any programmer is that programming mistakes do happen, and they happen
no matter how experienced the programmer is
...
NET
and Visual Web Developer can help you analyze and debug your code
...
aspx
...
EventArgs) Handles Me
...
aspx
...
The problem is that it doesn’t stop at the tenth element: it also
tries to assign a value to the eleventh element, which doesn’t exist
...
46
...
46
...
The easiest way to enable
debug mode it to use Visual Web Developer
...
If you ask it to, it’ll modify (or create) the Web
...


205

Chapter 5: Building Web Applications

Figure 5
...
Debugging a run-time error

Executing the page once again—this time, with debugging enabled—takes you
straight to the error in Visual Web Developer, as Figure 5
...

This interface tells you that the code has thrown an exception of type
IndexOutOfRangeException
...
NET, exceptions are the standard means by
which errors are generated and propagated
...
NET class (in this
case, the IndexOutOfRangeException class) that contains the details of an error
...
If the error isn’t caught and handled, as in this
case, it’s finally caught by the ASP
...

In Figure 5
...
Let’s see what your options are at this moment
...
If it’s not displayed, you can open it by accessing Debug >
Windows > Watch
...
Try typing
a(5) (or a[5] if you’re using C#) in the Watch window; you should see a display
like the one in Figure 5
...


Figure 5
...
Inspecting values using the Watch window

You could even type just a, then explore its members via the display shown in
Figure 5
...


Figure 5
...
The Watch window showing the contents of an array

Arrays and VB
This example reveals an interesting aspect of this array
...
In all
...
So an array called a that had
ten elements would have as its first element a(0), and a(9) as its last
...
NET versions of the language (which had one-based arrays in which the
first element would have been a(1), and the last would have been a(10)):
it adds an element for you
...

C# has always had zero-based arrays, so an array defined as a[10] will have
ten elements
...

If you switch to the Locals window (Debug > Windows > Locals) shown in Figure 5
...


Figure 5
...
The Locals window

Another nice feature of Visual Web Developer is that when you hover your
cursor over a variable, the editing window shows you at-a-glance information
about that variable
...
For example, you may find that your code isn’t generating the output
you expected
...

The most common way to get started with this kind of debugging is to set a
breakpoint in the code
...
When we click there, a red
bullet appears, and the line is highlighted with red to indicate that it’s a breakpoint, as Figure 5
...

Once the breakpoint is set, we execute the code
...
In debug mode, you can
perform a number of tasks:
❑ View the values of your variables or objects
...
This executes the
currently highlighted line, then pauses
...


208

Debugging with Visual Web Developer

Figure 5
...
Setting a breakpoint

❑ Step over any line of code by selecting Debug > Step Over
...

❑ Step out of any method by selecting Debug > Step Out
...

❑ Continue execution of the program normally by selecting Debug > Continue
...
If the execution is stopped as a result of an exception, choosing to
continue the execution will allow the error to propagate to the ASP
...

❑ Stop execution by selecting Debug > Stop Debugging
...


209

Chapter 5: Building Web Applications

All these commands are also available from the Debug toolbar, which is shown
in Figure 5
...


Figure 5
...
The Debug toolbar

This toolbar appears by default when you’re debugging, but if it doesn’t, you can
make it display by right-clicking the toolbar and selecting Debug
...
53, and the button on the extreme right gives you easy access to the
various debugging windows
...
53
...
NET can also throw the
following kinds of errors:
configuration errors

parser errors

Parser errors are caused by the use of incorrect syntax in an ASP
...
NET controls included in a web form will cause parser errors
...
config
file
...
config, and
the next time you try to load the application, an
error will occur
...


Other Kinds of Errors

If you try to execute a page that contains compilation errors with Visual Web
Developer, those errors will be signaled right away, and the page won’t be loaded
in the web browser (see Figure 5
...


Figure 5
...
Visual Web Developer warns about a compilation
error

If you’d like to try this for yourself, write some VB code, but terminate one of
the lines with a semicolon as if you were writing C# code, as shown in the snippet
below
...
Text = DateTime
...
ToString();
End Sub

If you try to run this code, Visual Web Developer will present you with the
message shown in Figure 5
...
If you choose Yes, a previous version of the code
that used to compile successfully will be executed
...
If you choose No,
Visual Web Developer will display a window called Error List
...
Moreover, hovering your cursor over the highlighted code will display
a tooltip containing a few details about the error, as Figure 5
...

After such a demonstration, I hope you agree that Visual Web Developer is a
fantastic tool
...
55
...
NET
will report errors by displaying a message in the browser window, as we saw in
Figure 5
...
The default error message that’s shown to remote users doesn’t
contain code or other sensitive data, but you can customize the page that’s displayed to visitors when errors occur using a Web
...

We define the customErrors element as a child of the system
...
config (excerpt)


...
aspx" />

...
We can then choose whether this error page
is shown to everybody, to nobody, or only to users who access the site from another network using the mode attribute
...
NET uses user-defined custom error pages,
instead of its default error page, for both local and remote users
...
NET uses its default error
page for both local and remote users
...


RemoteOnly

When mode has the RemoteOnly value, the ASP
...
RemoteOnly is the default value, and is generally
the safest option during development
...


Handling Exceptions Locally
As you can see, unless you handle any exceptions that are raised in your code
yourself, they’ll be caught by the debugger
...
NET runtime,
which displays the errors in the browser
...

The basic syntax of Try-Catch-Finally is as follows:
Visual Basic

Try
' Code that could generate the exception that you want to handle

213

Chapter 5: Building Web Applications

Catch ex As Exception
' Code that is executed when an exception is generated
' The exception's details are accessible through the ex object
Finally
' Code that is guaranteed to execute at the end, no matter if
' an exception occurred
End Try

The equivalent C# syntax looks like this:
C#

try
{
// Code that could generate the exception that you want to
// handle
}
catch (Exception ex)
{
// Code that is executed when an exception is generated
// The exception's details are accessible through the ex
// object
}
finally
{
// Code that is guaranteed to execute at the end, no matter
// if an exception occurred
}

As a basic rule of thumb, we’ll place inside the Try block any code that we suspect
might generate errors that we’ll want to handle
...
If the code in the Try block doesn’t
generate any exceptions, the code in the Catch block won’t execute
...

That’s an important point: the code in the Finally block will always execute, no
matter what! As such, it’s good practice to place any “mission-critical” code in
that block
...

Exceptions propagate from the point at which they were raised up through the
call stack of your program
...
So, if method A calls a method B, which in turn calls method C, the call
stack will be formed of these three methods, as Figure 5
...


214

Handling Exceptions Locally

Figure 5
...
A simple call stack

In this scenario, an exception that’s raised in method C can be handled within
the same function, provided the offending code is inside a Try/Catch block
...
If no method handles the exception, it will be intercepted either by the Visual Web Developer debugger or the
ASP
...

In the Try-Catch-Finally construct, both the Finally and Catch blocks are
optional
...

In more complex scenarios, you can use more layers of error handling
...
Exceptions are thrown using the Throw keyword
(throw in C#), like so:
Visual Basic

Try
' Code that could generate and exception that you want to handle
Catch ex As Exception
' Code that is executed when an exception is generated
Throw ex
End Try
C#

try
{
// Code that could generate the exception that you want to
// handle

215

Chapter 5: Building Web Applications

}
catch (Exception ex)
{
// Code that is executed when an exception is generated
throw ex;
}

We could modify our array example to include Try and Catch blocks like this:
Visual Basic

File: ErrorTest
...
vb (excerpt)

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
Load
Dim a(10) As Integer
Dim i As Integer
Try
For i = 1 To 11
a(i) = i
Next
Catch ex As Exception
messageLabel
...
Message
End Try
End Sub
C#

File: ErrorTest
...
cs (excerpt)

protected void Page_Load(object sender, EventArgs e)
{
int[] a = new int[10];
int i;
try
{
for (i = 0; i < 11; i++)
{
a[i] = i;
}
}
catch(Exception ex)
{
messageLabel
...
Message;
}
}

Provided you have a Label control named messageLabel in your web form, you’ll
see the message shown in Figure 5
...


216

Handling Exceptions Locally

Figure 5
...
Catching an exception

In the code above, we can see that the Catch block receives an Exception object
as a parameter
...
In our code, we use one of the Exception object’s many properties—in this case, Message—to display some information about the error
...
NET, all exceptions are
...
This
means that, in fact, each exception is a different class (in our case, ex is an
IndexOutOfRangeException object), but we can treat ex as the generic Exception
class to access the generic details of any error
...
For example, the
SqlException class, which is raised when database-related errors occur, includes
a collection of error messages (SqlError objects) in its Errors property
...

In complex application scenarios, you could even create your own exception
classes as specialized versions of Exception
...


Summary
In this chapter, you’ve learned just how powerful Visual Web Developer can be
...

We’ve taken a close look at Web
...
asax, which is where applicationwide events can be handled
...

Finally, we took a look at themes and master pages, which are powerful ways of
managing your site’s look and feel
...
NET’s validation
controls can help us ensure that our back-end systems are as secure as possible
...
To help developers with the most common
data validation tasks, ASP
...
This chapter will show you
how to use them
...
You could write client-side JavaScript code that validates the data
typed by the user directly into the browser (client-side validation), or you could
use server-side VB or C# code to validate the user input once the form has been
submitted to the server (server-side validation)
...
If users fail to enter their names into a text box, the
page automatically displays an error message
...
The process is quick and efficient, and good for the overall
user experience
...
Some

Chapter 6: Using the Validation Controls

browsers, such as those built into PDAs and mobile telephones, don’t support
JavaScript, so client-side validation doesn’t work for users of those browsers
...

While client-side validation is optional, server-side validation is not
...
Server-side validation is necessary because it’s our last line of defense
against bogus user data
...


Introducing the ASP
...
NET includes controls that make validation a snap
...
NET validation
controls, while primarily being useful for implementing client-side validation,
make it easier to implement server-side validation as well
...
NET validation
controls generate the JavaScript required for basic validation tasks for you (so
you don’t need to deal with any JavaScript code yourself); then, once the page
is submitted, you can use the controls to check on the server whether or not the
client-side validation was successful
...
NET’s validation controls provide client-side validation capabilities while
virtually eliminating the need for developers to know JavaScript
...
To use ASP
...

As our first step towards demonstrating the ASP
...
Then we’ll update the Dorknozzle intranet, adding validation features
to the Help Desk page
...

You can open Learning as a web site by selecting File > Open Web Site…,
navigating to the Learning folder (most likely C:\WebDocs\Learning\),
and clicking Open
...


220

Introducing the ASP
...
Create a file named Login
...
The parts that differ from the Visual Web Developer template are highlighted
...
aspx (excerpt)



Simple Login Page






Username:


runat="server"
ControlToValidate="usernameTextBox"
ErrorMessage="Username is required!" />




Password:

TextMode="Password" />
runat="server"
ControlToValidate="passwordTextBox"
ErrorMessage="Password is required!" />




Text="Submit" />







Here, we’ve added two RequiredFieldValidator controls, which force the user
to type some data into the referenced controls before the form can be submitted
...
It sets a couple of properties, whose names are pretty descriptive
(ControlToValidate, and ErrorMessage):
File: Login
...
The page should display as shown in Figure 6
...
When we click
the Submit button, we see instantly the error messages that tell us we forgot to
type in a username and password
...
1
...
NET validation controls is that they determine whether or
not the browser is capable of supporting client-side validation
...
NET
automatically includes the necessary client-side JavaScript; if not, it’s omitted
and the form is validated on the server
...
NET 2
...
NET, these controls demonstrated a tendency
to assume that non-Microsoft browsers, such as Firefox, do not support
JavaScript
...
NET’s client-side validation relies on JavaScript, clientside validation was not supported in those browsers and users had to rely
on these controls’ server-side validation
...
NET 2
...
However, it’s important not to forget that

222

Enforcing Validation on the Server

JavaScript can be disabled in any browser, so client-side validation cannot
be relied upon—we must always validate any submitted data on the server
...
NET 2
...
We activate this feature
by setting the SetFocusOnError property of the validation control to True
...

Let’s do that now:
File: Login
...
If both text boxes are empty, the first one will receive focus
...
There are many circumstances where processing
bad input data could have negative effects—for instance, it could produce runtime
errors, or cause bad data to be stored in your database
...
The typical point at which visitor
data is used in a login page is the Click event handler of the Submit button
...
This mimics what Visual Web Developer would do if you doubleclicked the button in Design View
...
You can add this between
tags in the head of the web form, or
place it in a code-behind file
...
aspx (excerpt)

Protected Sub submitButton_Click(s As Object, e As EventArgs)
submitButton
...
aspx (excerpt)

protected void submitButton_Click(object sender, EventArgs e)
{
submitButton
...
However, if you disable your browser’s
JavaScript, you’ll see the label on the Button control change to Clicked! Obviously,
this is not an ideal situation—we’ll need to do a little more work to get validation
working on the server side
...


Disabling JavaScript in Opera
To disable JavaScript in Opera, go to Tools > Preferences…, click the Advanced tab, select Content in the list on the left, and uncheck the Enable
JavaScript checkbox
...
There, select the zone for which you’re changing
the settings (the zone will be shown on the right-hand side of the browser’s
status bar—it will likely be Local Intranet Zone if you’re developing on the
local machine) and press Custom Level…
...


ASP
...
All we need to do is to check the Page object’s IsValid property, which only
returns True if all the validators on the page are happy with the data in the controls they’re validating
...

Let’s add this property to our Click event handler:
Visual Basic

File: Login
...
IsValid Then
submitButton
...
Text = "Invalid!"
End If
End Sub
C#

File: Login
...
IsValid)
{
submitButton
...
Text = "Invalid!";
}
}

Load the page again after disabling JavaScript, and press the Submit button
without entering any data in the text boxes
...
2
...
2
...
IsValid returned False
...
If JavaScript were enabled,
the validator controls would prevent the page from submitting, so the code that
changes the Button’s text wouldn’t execute
...
IsValid is True
before you use any of the validated data, you have a bulletproof solution that’s
guaranteed to avoid bad data entering your application through any browser
...


Using CausesValidation
There are cases in which you might decide to disable validation when a certain
event is triggered
...
You’d probably want the Cancel
button to work regardless of whether valid data has been entered, otherwise
users won’t be able to cancel the process before typing in some valid data!
You can make Cancel work at all times by setting the CausesValidation
property of the button to False
...
To illustrate this point, let’s add a password confirmation text
box just after the password text box’s RequiredFieldValidator:

226

Enforcing Validation on the Server

File: Login
...
3 illustrates
...
3
...
NET reserves space for its validator controls by default
...
You may want to set this option when using the
ValidationSummary control (which we’ll cover later) to display a list of validation errors for the entire page, in which case you won’t want each validation
control to display its own error message separately
...
With this mode, the validator occupies

space on the generated form even if it doesn’t display anything
...
3) if the validation is passed
...
If we set this property
for all of the validation controls in our page, the two password TextBox controls
will appear side by side until one of them fails validation
...
aspx (excerpt)



Password and Confirmation:

TextMode="Password" />
ControlToValidate="passwordTextBox"
ErrorMessage="Password is required!"
SetFocusOnError="True" Display="Dynamic" />
TextMode="Password" />
runat="server" ControlToValidate="confirmPasswordTextBox"
ErrorMessage="Password confirmation is required!"
SetFocusOnError="True" Display="Dynamic" />



228

Using Validation Controls

Using Validation Controls
Now that you have an understanding of what validation controls can do, let’s
have a look at the different controls that are available in ASP
...
4 illustrates
...
4
...
Once a validation control is inserted, it validates an
existing control elsewhere on the page, and presents an error message to the user
if necessary
...
NET validation controls in detail
...

It does exactly what its name suggests: it makes sure that a user enters a value
into a web control
...
aspx (excerpt)


Username:


ControlToValidate="usernameTextBox"
ErrorMessage="Username is required!"
SetFocusOnError="True" Display="Dynamic" />




Password and Confirmation:

TextMode="Password" />
ControlToValidate="passwordTextBox"
ErrorMessage="Password is required!"
SetFocusOnError="True" Display="Dynamic" />
TextMode="Password" />
runat="server" ControlToValidate="confirmPasswordTextBox"
ErrorMessage="Password confirmation is required!"
SetFocusOnError="True" Display="Dynamic" />



As you can see, three RequiredFieldValidator controls are used on this page
...
These assignments are made using the ControlToValidate property of
the RequiredFieldValidator controls
...


230

CompareValidator

CompareValidator
One of the most useful validation controls is the CompareValidator control,
which performs a comparison between the data entered into a given control and
some other value
...

Let’s look at an example that builds on the login example from the previous section
...
Make the following changes to Login
...
aspx (excerpt)

TextMode="Password" />

TextMode="Password" />

ControlToCompare="passwordTextBox"
ControlToValidate="confirmPasswordTextBox"
ErrorMessage="Your passwords do not match up!"
Display="Dynamic" />



Run the page and enter different passwords into the two fields
...
5 shows
...
5
...
aspx (excerpt)

ControlToValidate="confirmPasswordTextBox"
ErrorMessage="Password confirmation is required!"
SetFocusOnError="True" Display="Dynamic" />
ControlToCompare="passwordTextBox"
ControlToValidate="confirmPasswordTextBox"
ErrorMessage="Your passwords do not match up!"
Display="Dynamic" />

The only difference is that in addition to a ControlToValidate property, the
CompareValidator has a ControlToCompare property
...
So, in our example, the
ControlToValidate property is set to the confirmPasswordTextBox, and the
ControlToCompare property is set to the passwordTextBox
...
CompareValidator can check whether the entered value is equal to,
less than, or greater than, any given value
...
aspx (excerpt)



Age:


ControlToValidate="ageTextBox"
ErrorMessage="Age is required!"
SetFocusOnError="True" Display="Dynamic" />
Operator="GreaterThan" Type="Integer"
ControlToValidate="ageTextBox" ValueToCompare="15"
ErrorMessage="You must be 16 years or older to log in" />



In this case, the CompareValidator control is used to check that the user is old
enough to log in to our fictitious web application
...
This property can take on
any of the values Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan,

232

RangeValidator

LessThanEqual, or DataTypeCheck, which we’ll look at shortly
...

Finally, we use the ValueToCompare property to make sure that the user’s age is

greater than 15
...

We can also use the CompareValidator control to perform data type checks
...
aspx (excerpt)



Birth Date:


Operator="DataTypeCheck" Type="Date"
ControlToValidate="birthDateTextBox"
ErrorMessage="You must enter the date in a valid format!"
SetFocusOnError="True" Display="Dynamic" />



As you can see, the Operator property of the CompareValidator control is set
to perform a DataTypeCheck, and the Type property is set to Date
...

The constituents of a “valid” date will depend on the regional settings on your
web server
...
For instance, we could make sure that users who
visit our web site were born in a certain decade
...

Let’s continue by expanding Login
...
aspx (excerpt)



Birth Date:


233

Chapter 6: Using the Validation Controls


Type="Date" ControlToValidate="birthDateTextBox"
MinimumValue="1/1/1970" MaximumValue="12/31/1979"
ErrorMessage="You must've been born in the 1970s to use
this web site!" />



Take Care when Specifying Dates
If you’re outside of the US, you may need to modify the above example
...
In the UK and Australia, they’re specified in day-month-year order, and in other countries, the
year is specified first
...
NET runtime will be expecting you to specify
dates in your local format, so adjust the values of the MinimumValue and
MaximumValue properties accordingly
...

Our RangeValidator control checks whether the date entered falls within the
1970s, and shows an error message similar to Figure 6
...


Figure 6
...
Using the RangeValidator control

Note that the Type property of the RangeValidator control specifies the data
type that’s expected in the control with which it’s associated: if some other data
type is entered into this field, it fails validation
...


234

ValidationSummary

ValidationSummary
Imagine we have a form that contains many form fields
...
The ValidationSummary control can alleviate
this problem by presenting the user with a list of error messages in one place on
the page
...
Add it to the end of
your Login
...
aspx (excerpt)



OnClick="submitButton_Click" />







When the user clicks the Submit button, the ValidationSummary is populated
automatically with a list of all the errors on the page, as we can see in Figure 6
...


Figure 6
...
Using the ValidationSummary control

235

Chapter 6: Using the Validation Controls

This control isn’t particularly good-looking, but you can see its potential
...

If you set the ShowMessageBox property of the ValidationSummary control to
True, the list of errors will be shown in a JavaScript alert box similar to Figure 6
...
The server-side list will still be shown to users who don’t have JavaScriptenabled browsers
...
8
...
Regular expressions are powerful
tools for manipulating strings, and are supported by many programming languages
...
Consider, for instance,
the following regular expression:
^\S+@\S+\
...
), then one or more non-whitespace
characters, followed by the end of the string
...
com
❑ zac@host
...
com
❑ joe_bloggs@yahoo
...
uk
However, the regular expression would fail if the user typed in one of these entries:

236

RegularExpressionValidator

❑ books@sitepoint
❑ joe bloggs@yahoo
...
uk
Although regular expressions cannot check to see if the email address itself is
valid, they can, at the very least, provide a means for us to determine whether
or not the user has entered a string of characters that has all the key components
of a valid email address
...

File: Login
...
\S+$"
ErrorMessage="You must enter a valid email address!" />



The important property within this control is ValidationExpression, to which
we assign the regular expression that’s appropriate to handle our custom validation
functionality
...
9 shows the error message that appears when a user enters
an incorrect email address
...
9
...
Many of the other regular expressions presented
here are nowhere near as rigorous as they could be, but are still quite useful
...
F
...
1 outlines the usage of some simple regular expressions
...
1
...
\S+$

web URL

^https?://\S+\
...
2, you
should begin to see how they work
...
F
...

http://www
...
com/
3
http://www
...
com/article/regular-expressions-php
2

238

CustomValidator
Regular Expressions in JavaScript4
another great article, this time on the use of regular expressions with JavaScript

Table 6
...
Common regular expression components and their
descriptions
Special
Character

Description


...
For example, \
...
NET Framework SDK Documentation
...
NET allow you to handle many kinds
of validation, yet certain types of validation cannot be performed with these
built-in controls
...
sitepoint
...
The CustomValidator control can be helpful in this situation,
and others like it
...
aspx (excerpt)

...
w3
...
dtd">


CustomValidator Control Sample





New Username:


ControlToValidate="usernameTextBox"
OnServerValidate="CheckUniqueUserName"
ErrorMessage="This username already taken!" />



OnClick="submitButton_Click" Text="Submit" />






240

CustomValidator

C#

File: CustomValidator
...
0 Transitional//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-transitional
...
Value
...
IsValid = false;
}
}
void submitButton_Click(Object s, EventArgs e)
{
if(Page
...
Text = "Valid";
}
else
{
submitButton
...
At the
moment, our list of usernames is limited to zak and cristian
...
IsValid is set to False, and the error message
is displayed; otherwise, we assume that the username is valid
...
IsValid property, e
...

Although this example shows a very simple CustomValidator, you can certainly
imagine the possibilities this class makes available
...

For details, refer to the
...


Validation Groups
A very useful new feature in ASP
...
0, validation groups allow us to validate
individual parts of a web page independently of its other sections
...
For example, consider the scenario of a single page
that contains a login form and a quick registration form, each with its own Submit
button and its own set of validation controls
...

The solution to this problem is to set the controls in each of the boxes within
different validation groups
...
aspx (excerpt)

...
w3
...
dtd">


Validation Groups Demo


242

Validation Groups




Login




Username:


runat="server" ControlToValidate="usernameTextBox"
ErrorMessage="Username is required!"
SetFocusOnError="True" ValidationGroup="Login" />




Password:

runat="server" TextMode="Password" />
runat="server" ControlToValidate="passwordTextBox"
ErrorMessage="Password is required!"
SetFocusOnError="True" ValidationGroup="Login" />



ValidationGroup="Login" />



Register




Username:


runat="server" ControlToValidate="newUserNameTextBox"
ErrorMessage="Username is required!"
SetFocusOnError="True" ValidationGroup="Register" />




Password:

TextMode="Password" />
runat="server" ControlToValidate="newPasswordTextBox"
ErrorMessage="Password is required!"

243

Chapter 6: Using the Validation Controls

SetFocusOnError="True" ValidationGroup="Register" />



Text="Register" ValidationGroup="Register" />






Executing this page reveals the two sets of controls: one for logging in an existing
user, and another for registering a new user
...

Clicking the Log In button triggers only those validators that share that button’s
ValidationGroup setting, as Figure 6
...


Figure 6
...
Triggering the Login ValidationGroup

Likewise, clicking the Register button triggers the second set of validators, and
deactivates the first, as Figure 6
...


244

Updating Dorknozzle

Default Validation Groups
Controls that aren’t specifically assigned to any validation group are aggregated into a default validation group
...


Finally, remember that Page
...
e
...
To verify the validity of
another group on the page, we use the Page
...


Figure 6
...
Activating the RegisterValidationGroup

Updating Dorknozzle
Now that you’ve spent some time with validation controls, let’s use them to update Dorknozzle’s Help Desk page
...

❑ The station number must be a valid number
...

❑ A description of the problem must be entered
...
Go to File > Open Web Site… and select the
Dorknozzle project
...


After Dorknozzle loads, open HelpDesk
...
aspx (excerpt)

<%@ Page Language="VB" MasterPageFile="~/Dorknozzle
...
aspx
...
"
Display="Dynamic" />



Problem Category:


246

Updating Dorknozzle

CssClass="dropdownmenu" />



Problem Subject:

CssClass="dropdownmenu" />



Problem Description:

CssClass="textbox" Columns="40" Rows="4"
TextMode="MultiLine" />
ControlToValidate="descriptionTextBox"
ErrorMessage="
You must enter a description!"
Display="Dynamic" />



CssClass="button" Text="Submit Request" />




Now execute the project, and select the Help Desk page from the menu
...
12
shows
...
12
...
When we finally do something with this
data, we don’t want our server-side code to try to work with invalid data
...

Stop the project from within Visual Web Developer, and open HelpDesk
...
There, double-click the Submit Request button to have its Click
event handler generated for you
...
aspx
...
EventArgs) Handles submitButton
...
IsValid Then
' Code that uses the data entered by the user
End If
End Sub
C#

File: HelpDesk
...
cs (excerpt)

protected void submitButton_Click(object sender, EventArgs e)
{
if (Page
...
This approach involves setting a property, such as OnClick,
on the control, as shown here:
C#

File: HelpDesk
...
NET to call a method named submitButton_Click
whenever this button is clicked
...

However, if you’re using VB, this property is not added
...
Click)
...
aspx
...
EventArgs) Handles submitButton
...


249

Chapter 6: Using the Validation Controls

We’ll expand the code inside this method in later chapters, but for the time being,
you can rest assured that you’ve put the validation mechanism in place
...
NET are very
powerful
...

In the next chapter, we’ll begin to introduce you to the challenges—and rewards!—involved in working with databases
...
Whether you’re building a company-wide intranet that can only be accessed
by employees, or a feature-rich ecommerce site that millions will visit, you’ll need
a system for storing information
...

In 1970, E
...
Codd, an employee of IBM, proposed his idea for what would become the first relational database design model
...
The concept of relational data
stemmed from the fact that data was organized in tables, and relationships were
defined between those tables
...
By the end of this book, our site will be able to do all sorts of
things, but beside these bells and whistles, our company intranet will need to do
one core job: keep track of the employees in our company
...
But, unless Dorknozzle is a very small
company, a single page that contained all the details of every employee would
be destined to become unusably large
...
Sure, this approach might
mean there’s a bit of typing to do, but it’s the kind of job you can assign to the
boss’s son on his summer internship
...
By now, Dorknozzle Jr is back at school,
and the mind-numbing job of manually updating each of the employee profile
pages falls right in your lap
...
A database
is a collection of data organized within a framework that can be accessed by
programs such as your SPINET web site
...

Such a collection of data needs to be managed by some kind of software—that
software is called a database server
...
Other popular database server software products
include Oracle, DB2, PostgreSQL, MySQL, and others
...
First, instead of having to write an HTML file for

252

What is a Database?

each employee profile page, you could write a single ASP
...
This single form could be updated quite easily in the event of corporate
re-branding or some other disaster
...
The web
form would take care of the rest, automatically displaying the new employee
profile along with the others when it fetched the list from the database
...
A
database is composed of one or more tables
...
Each table in a database has one or more columns (or
fields)
...
In our example, the Employees table might have columns for the employees’
names, network usernames, and phone numbers
...

These rows and columns would form a table that looks like the one shown in
Figure 7
...


Figure 7
...
Structure of a typical database table

Notice that, in addition to columns for the employees’ names, usernames, and
telephone numbers, I included a column named Employee ID
...
In this particular case, you might consider using an existing piece
of data as the unique identifier
...
However, that’s something for our network
administrator to worry about
...
This gives us an easy way to
refer to each person, and let us keep track of which employee is which
...

So, to review, Figure 7
...

Each row in the table contains four fields, one for each column in the table: the
employee’s ID, name, username, and telephone number
...
There are many ways to interact with SQL
Server, but for starters, we’re just interested in using it as a visual tool to facilitate
basic administrative tasks
...

We’ll call the database that will store the data for our sample project
“Dorknozzle
...
You can use either Visual
Web Developer or SQL Server Management Studio to create the Dorknozzle
database
...


254

Creating a New Database Using Visual Web Developer

Creating a New Database Using Visual Web
Developer
Visual Web Developer’s Database Explorer window gives you access to most
database-related features
...
Right-click the Data Connections node and select Add Connection… from the context menu, as shown in Figure 7
...


Figure 7
...
Adding a new database connection

If you’ve installed SQL Server using the instructions we stepped through in
Chapter 1, select Microsoft SQL Server from the Choose Data Source dialog that
appears, and click Continue
...
Enter the following data:
❑ Set Server name to localhost\SqlExpress
...

❑ Click Test Connection to ensure you can successfully connect to SQL Server
using the data you’ve provided
...
Click OK
...

Click Yes
...
3
...
You can expand it to view
its contents, as Figure 7
...


Creating a New Database Using SQL Server
Management Studio
To start SQL Server Management Studio, which we learned to install in Chapter 1,
select Start > All Programs > Microsoft SQL Server > SQL Server Management Studio
Express
...
4
illustrates
...
If you’ve just installed SQL Server, you’ll only have installed the system
databases, which are grouped under a System Databases node
...
5 below,
you can see that I have another database, named BalloonShop, on my SQL
Server
...
4
...
5
...
In the dialog that appears, enter Dorknozzle into
the Database name field, then click OK
...
Tables can be thought
of as the drawers in a filing cabinet: just as we could separate different information
into different drawers within our filing cabinet, we can break information about
employees, departments, and help desk requests into different tables
...
They know what kinds of data they’re allowed to
store, they can relate to data contained in other tables, and they can be searched
and manipulated with a very powerful language called SQL (which you’ll learn
about in Chapter 8)
...
While SQL
Server Management Studio is more powerful, both tools can be used for basic
tasks such as creating database tables
...
Before we do, it’s worth
giving some thought to how many tables our application will need, and exactly
what they’ll contain
...
Entities are the
rows or records in our table, and would include the employees Zak Ruvalcaba
and Cristian Darie
...
The logical design shows what kinds
of data our database will need to store, and outlines the relationships that we
want to exist between specific pieces of data
...
This is taken
care of in the physical design phase, in which we create a practical blueprint
that allows us to improve database speed, enable relationships between different
tables, or implement other advanced features—basically, to optimize our database
in various ways
...
Let’s take a look at an example, so you
can see what I mean
...


258

Creating Database Tables

To achieve this, it might seem logical simply to add a column to the Employees
table we discussed above; Figure 7
...


Figure 7
...
The Employees table

It looks pretty good, right? Well, it’s okay in theory
...
If you make even the
slightest spelling error, then, as far as the database is concerned, you have a
new department
...
” And what if Dorknozzle Sr decides to rename one of the departments? You might try to update all the affected employee records with the
new department name, but, even if you miss just one record, your database
will contain inconsistent information
...

❑ It would be natural for you to rely on your database to provide a list of all
the departments in the company, so you could, for example, choose to view
a list of employees in a particular department
...
Database design experts call this
a delete anomaly
...
Instead of storing the
information for the departments in the Employees table, let’s create an entirely
new table for our list of departments
...
We can use those de-

259

Chapter 7: Database Design and Development

partment IDs in our Employees table to associate departments with employees
...
7
...
7
...
and Implementation
As this example has shown, the way you’d naturally draw your database
design on paper, and the best way to implement the design in practice, can
be two different things
...


What these tables show are four employees and three departments
...
Notice also that, as each department appears only once in the database, and appears independently of the employees who work in it, we’ve avoided the problems outlined above
...
This approach illustrates an important rule of
thumb that we must keep in mind when designing databases:
Each type of entity about which we want to be able to store information should be given its
own table
...
We need to think of the design
in terms of the entities that we want to track, and come up with a preliminary
list of tables
...
When you’re done, compare your list to the one below, and see how you
did!
Employees
This table keeps track of our company’s employees, each of which is associated
with a department
...

Help Desk Problem Reports
This table stores the problem reports that have been filed at Dorknozzle’s
employee help desk
...

Help Desk Categories
The categories that are available for help desk items (“Hardware,” “Software,”
etc
...

Help Desk Subjects
The subjects that are available for help desk items (“Computer crashes,” “My
chair is broken,” etc
...

Help Desk States
This table stores the various states in which a help desk item can exist (“open”
or “closed”)
...
Through this process, we work to
build a high-level definition of the data that needs to be saved
...

As you analyze the data that needs to be stored, you may come across items that
we overlooked when we designed the site in Chapter 5, such as help desk item
categories, subjects, and states, which aren’t obvious entities in our application’s
current design
...
This approach makes it easy to execute
changes to the list in future; it also reduces the amount of disk space required by
your database, and helps you to avoid redundancy, as you store only single instances of department names, strings like “I can’t print,” and so on
...
Although I’ll speak a bit more about normalization before the
end of this chapter, I’ll only ever discuss it in an informal, hands-on (i
...
nonrigorous) way
...
If you want more information
on the topic, stop by DataModel
...
In particular, check out the Rules of Normalization
in the Data Modeling section of the site
...
In the next section, we’ll look at the columns
within those tables, and discuss how we can ascertain their characteristics
...
Once you understand how
to create a new table, you can create the rest of the tables for the Dorknozzle
application in your own time, based on the descriptions I’ll provide
...

Once you’ve outlined all your tables, the next step is to decide what pieces of
information will be included within those tables
...
Let’s see how we can define these
columns as we create the Employees table for the Dorknozzle database
...
That’s right—as with the data we’re storing in our VB
...


1
2

262

http://www
...
org/
http://www
...
org/NormalizationRules
...
Below is a list of
the common data types that we’ll use in this book:
int
Use the int data type when you need to store whole integers
...

float
Use the float data type when you're working with very large numbers or very
small numbers
...

money
The money data type should be used to store monetary data, such as prices
for a product catalog
...

bit
Use the bit data type when a condition is either true (represented as 1) or
false (represented as 0)
...
It’s very useful when you want to sort items in your table chronologically
...
This is most commonly used
data type because it stores names, descriptions, and the like
...
For example,
nvarchar(50) specifies an field that can hold up to 50 characters
...

nchar(n)
The nchar data type is similar to nvarchar in that it stores strings, but a field
of this type will always store strings of the defined size
...

For example, if you’re working with an nchar(6) field (where the 6 in parentheses indicates that the field can hold six characters), and you add the word
“test” to the field, two space characters will be appended to the end of the
word so that all six characters are used
...


money, money, money
Sometimes, you may see poorly designed databases use float to store monetary
data
...
money, on
the other hand, is not susceptible to these errors and is a much better choice
...
nvarchar and nchar have non-Unicode cousins named varchar and char,
which you can use if you’re sure you won’t need to store Unicode data
...
Unicode is a very widely supported standard, so it’s strongly recommended you stick with nvarchar and nchar
...
For example, sorting
data by a datetime column will cause the records to be sorted chronologically,
rather than alphabetically or numerically
...
Other properties you’ll use frequently include:
NULL

In database speak, NULL means “undefined
...
If you set an employee’s mobile telephone number to NULL, for example, this could represent the
fact that the employee doesn’t have a mobile telephone
...

For instance, you might create a department with the name NULL to represent
a mysterious department with no name, but obviously, this is far from ideal
...
In our example, we’d like every department to have
a name, so we shouldn’t allow the Name column to allow NULLs
...
We won’t be using this feature
when we create Dorknozzle, but it’s good to know you have this option
...
If you set a column as an
IDENTITY column, SQL Server will generate numbers automatically for that

column as you add new rows to it
...
To generate subsequent numbers, the identity column
adds a given value to the seed; the value that’s added is called the identity
increment
...
If the identity seed
were 5 and the identity increment were 10, the generated numbers would be
5, 15, 25, and so on
...
When you use
IDENTITY, the generated values will always be unique
...
Note also that the column can never
contain NULL
...
Both 0 and an empty string are
values; NULL defines the lack of a value
...
Many people
seem to believe that columns with default values won’t store NULL
...
You can modify a record after it was created, and change
any field that will allow it to NULL
...
A default value does make things easier when we create new rows,
but it’s not as vital as is correctly allowing (or disallowing) NULL in columns
...
In the world of relational databases, each
row in a table must be identified uniquely by a column called a key, on which all
database operations are based
...
Imagine that your program needs to update or delete the record for
John Smith, and there are several people with that name in your organization
...

We can avoid these kinds of problems only by using a system that uniquely
identifies each row in the table
...
1
...

After all, that’s what the network administrator uses them for, so why shouldn’t
you? It’s true that this column uniquely identifies each row in the table, and we
call such a column a candidate key
...
Firstly, network
usernames have been known to change, and such a change would wreak havoc
on any database of more than a couple of tables
...
Secondly, non-numeric keys require
much more processing power than simple numeric ones
...

The column that we choose to uniquely identify a row in a table in practice is
called the primary key
...


Multi-column Keys
To make the concept of keys easier to understand, we kept the definition
simple, although it’s not 100% technically correct
...
If
the key is made up of multiple columns, the set of values in those columns
must be unique for any given record
...


Although we usually refer to primary keys as if they were columns, technically they
are constraints that we apply to the existing columns of a table
...
When the primary key constraint is set on a
column, the database will refuse to store duplicate values in that column
...

Primary keys composed of a single column, such as Employee ID, are frequently
used in conjunction with the IDENTITY property
...
The IDENTITY
property helps us by always generating a new value that hasn’t already been used
in the primary key
...
It’s true that the IDENTITY property always generates
unique values, but it doesn’t necessarily enforce them
...
This table contains three records that are
likely to contain the automatically generated values 1, 2, and 3 in the
IDENTITY column
...
The IDENTITY column will
continue to generate unique values (4, 5, 6, and so on), but it doesn’t guarantee the column remains unique
...
If you’re
using Visual Web Developer, expand the database node in Database Explorer,
right-click Tables, and select Add New Table, as shown in Figure 7
...


Figure 7
...
Adding a new table in Visual Web Developer

267

Chapter 7: Database Design and Development

If you prefer SQL Server Management Studio, you need to follow a similar procedure
...
9
...
9
...
10—it looks the same in both Visual Web Developer and SQL Server
Management Studio
...
To set additional
properties, you need to use the Column Properties pane
...
This will reveal the (Is Identity) dropdown list, which should be set to Yes for an IDENTITY column, as Figure 7
...

To set a column as the primary key, we can select Table Designer > Set Primary
Key, or click the little golden key icon in the Table Designer toolbar while the
column is selected
...
11 illustrates
...
10
...
11
...
1
...
1
...
When you’re asked
to name the table, type Employees and click OK
...
11
...
SQL Server Management
Studio prepends dbo
...
Don’t worry about this for now—we’ll explore the topic of database users
in some detail later
...
You’ll be taken back to the screen
that shows the structure of the table (shown in Figure 7
...


270

Creating the Remaining Tables

Creating the Remaining Tables
Let’s create the rest of the database tables
...
2 to Table 7
...
Later in this chapter, we’ll discuss how these tables work
...


Table 7
...
The Departments table
Column
Name

SQL Data
Type

DepartmentID int
Department

nvarchar(50)

Identity

Allow Null

Primary Key

Yes

No

Yes

No

No

No

Table 7
...
The HelpDesk table
Column
Name

SQL Data
Type

Identity

Allow Null

Primary Key

RequestID

int

Yes

No

Yes

EmployeeID

int

No

No

No

StationNumber int

No

Yes

No

CategoryID

int

No

No

No

SubjectID

int

No

No

No

Description

nvarchar(50)

No

Yes

No

StatusID

int

No

No

No

Table 7
...
The HelpDeskCategories table
Column
Name

SQL Data
Type

Identity

Allow Null

Primary Key

CategoryID

int

Yes

No

Yes

Category

nvarchar(50)

No

No

No

271

Chapter 7: Database Design and Development

Table 7
...
The HelpDeskSubjects table
Column
Name

SQL Data
Type

Identity

Allow Null

Primary Key

SubjectID

int

Yes

No

Yes

Subject

nvarchar(50)

No

No

No

Table 7
...
The HelpDeskStatus table
Column
Name

SQL Data
Type

Identity

Allow Null

Primary Key

StatusID

int

Yes

No

Yes

Status

nvarchar(50)

No

No

No

Using SQL Scripts
Yep, there’s a lot of data to type in! While we recommend that you create
the tables yourself by defining the fields outlined here, you can achieve the
same goal using an SQL script that’s included in this book’s code archive
...

If you want to use the downloadable script, we recommend you have a look
over the following tables to get an idea of the structures we’ll be creating,
then read the section called “Executing SQL Scripts” that follows
...
The other tables will be used to store help desk requests; we’ll discuss
these in more detail in the following pages
...
sql script included in the book’s code archive to create the tables for
you
...
After
you log in, click the New Query button on the toolbar (or select File > New >
Query with Current Connection)
...
sql
script into the window that opens, and press F5 to execute the commands
...


272

Populating the Data Tables

The SQL scripts included in the code archive contains all the commands required
for this entire chapter—it even creates the sample data and table references that
are covered later
...
Suppose that our intranet web application was a real
application
...

Once the data structures are in place, adding rows of data is as easy as typing
information into the cells in the Datasheet View of a table, which looks a bit
like a spreadsheet
...

You can use the window that opens to start adding data
...
Table 7
...
11 represent the tables and
data you should add
...
You need to be careful, because an ID value will never
be generated twice on the same table
...


Keep in mind that a new row is saved to the database at the moment that you
move on to the next row
...


273

Chapter 7: Database Design and Development

Table 7
...
The Departments table
EmployeeID (Primary Key)

Department

1

Accounting

2

Administration

3

Business Development

4

Customer Support

5

Executive

6

Engineering

7

Facilities

8

IT

8

Marketing

10

Operations

Table 7
...
The Employees table
Emp’ID Dep’tID
(Primary
Key)

Name

U’name

P’word

M’Phone

1

5

Zak
zak
Ruvalcaba

San CA
Diego

555-555-5551

2

9

Jessica
jessica jessica San CA
Ruvalcaba
Diego

555-555-5552

3

6

Ted
Lindsey

ted

ted

San CA
Diego

555-555-5555

4

6

Shane
Weebe

shane

shane

San CA
Diego

555-555-5554

5

9

David
Levinson

david

david

San CA
Diego

555-555-5553

6

274

zak

City State

1

Geoff Kim geoff

geoff

San CA
Diego

555-555-5556

Populating the Data Tables

The Employees table contains a few more columns than those outlined here, but,
due to the size constraints of this page, I’ve left them out
...


Table 7
...
The HelpDeskCategories table
CategoryID (Primary Key)

Category

1

Hardware

2

Software

3

Workstation

4

Other/Don't Know

Table 7
...
The HelpDeskStatus table
StatusID (Primary Key)

Status

1

Open

2

Closed

Table 7
...
The HelpDeskSubjects table
SubjectID (Primary Key)

Subject

1

Computer won't start

2

Monitor won't turn on

3

Chair is broken

4

Office won't work

5

Windows won't work

6

Computer crashes

7

Other

What IDENTITY Columns are not For
In our examples, as in many real-world scenarios, the ID values are sequences
that start with 1 and increment by 1
...
The ID is really an arbitrary number that we know to be unique;
no other information should be discerned from it
...
When
we draw tables on paper to decide the logical design of a database, we actually
include significant information about our application (and about the business
for which the application is used)
...
12, for example, we can see that
the employee Zak Ruvalcaba works in the Executive department
...
12
...
However, as we
did so, we kept the significance of the original information intact by including
references to the new tables in our existing table
...
13 illustrates
...
Instead, each employee record refers to the ID of the appropriate department
...

These kinds of relationships exist between the HelpDesk, HelpDeskCategories,
HelpDeskStatus, and HelpDeskSubjects tables
...
Now, if we stored all the request information in a single
table, its records would look like those shown in Figure 7
...


276

Relational Database Design Concepts

Figure 7
...
Related data about employees and departments

Figure 7
...
Information about help desk requests

In order to eliminate redundant data here, we’ve decided to store pieces of this
data in separate tables, and to reference those tables from the HelpDesk table
...
14 that’s not likely to repeat very frequently
are the description and the station number
...

Given these requirements, we split the information from Figure 7
...

❑ HelpDeskSubject contains the possible request subjects
...


277

Chapter 7: Database Design and Development

❑ The HelpDesk table stores the help desk requests by referencing records from
the other tables, and adding only two original pieces of data itself: the help
desk request description, and the station number
...
The relationships are so
important that the database has tools to protect them
...

In our database’s HelpDesk table, the data depicted in Figure 7
...
12
...
12
...


Foreign Keys
Technically speaking, a foreign key is a constraint that applies to a column that
refers to the primary key of another table
...

Unlike primary key columns, a foreign key column can contain NULL, and almost
always contains repeating values
...
Take a look at the examples shown in Table 7
...
14
...
13
...
14
...
Notice that the DepartmentID primary
key in the Departments table is unique, but the DepartmentID foreign key
within the Employees table may repeat
...
However, as with primary keys, just
having the correct fields in place doesn’t mean that our data is guaranteed to be
correct
...

SQL Server won’t mind making the change for you, so if you tried this in practice,
you’d end up storing invalid data
...

The easiest way to create foreign keys using Visual Web Developer or SQL
Server Management Studio is through database diagrams, so let’s learn about
them
...
The good news is that you have access to a great feature called
database diagrams, which makes it a cinch to create foreign keys
...

Database diagrams weren’t created specifically for the purpose of adding foreign
keys
...
However, the diagrams editor included in
Visual Web Developer and SQL Server Management Studio is very powerful, so
you can use the diagrams to create new tables, modify the structure of existing
tables, or add foreign keys
...
To create a database
diagram in Visual Web Developer, right-click the Database Diagrams node, and
select Add New Diagram, as shown in Figure 7
...

The process is similar in SQL Server Management Studio, which, as Figure 7
...

The first time you try to create a diagram, you’ll be asked to confirm the creation
of the database structures that support diagrams
...
17
...
15
...
16
...
17
...
18
...
18 will ask you which of your database
tables you want included in the diagram
...

Click Add until all the tables are added to the diagram
...
Once you’ve
added all the tables, click Close
...
19
...
The zooming feature may prove useful here! Select File > Save
Diagram1 (or similar) to save your new diagram
...

Now, if you right-click any table in the diagram, you’ll gain access to a plethora
of possibilities, as Figure 7
...
This menu, along with the other diagramming features, are identical in Visual Web Developer and SQL Server Management
Studio
...
19
...
20
...
If you choose Standard, you’ll see a full-blown version of the table definition;
as Figure 7
...


Figure 7
...
The standard table view

Implementing Relationships in the Dorknozzle
Database
Every table in the Dorknozzle database has a relationship with another table
...

Let’s give it a try
...
22
...
22
...
23
...
23
...
23, and click OK
...
24 will appear, allowing you to tweak
numerous options that relate to the new foreign key
...


Figure 7
...
Editing the foreign key options

285

Chapter 7: Database Design and Development

After creating the foreign key, make a quick test to ensure that the relationship
is indeed enforced
...
You should see an error like the one pictured in Figure 7
...


Figure 7
...
The foreign key disallowing the addition of invalid
data

If you tried to delete a department with which employees were associated, you’d
generate a similar error
...
15 shows the foreign keys that we need to establish in the Dorknozzle
database
...
Go ahead and create all the foreign keys outlined
in Table 7
...


Table 7
...
The relationships in the Dorknozzle database
Primary Key

Foreign Key

DepartmentID in the table Departments DepartmentID in the table Employees
EmployeeID in the table Employees

EmployeeID in the table HelpDesk

CategoryID in the table HelpDeskCategories

CategoryID in the table HelpDesk

SubjectID in the table HelpDeskSubjects

SubjectID in the table HelpDesk

StatusID in the table HelpDeskStatus

StatusID in the table HelpDesk

When it’s complete, your relationship diagram should resemble Figure 7
...
After
you add the relationships, save your changes by selecting File > Save Dorknozzle
...


286

Diagrams and Table Relationships

Figure 7
...
Creating and visualizing table relationships

Now that you’ve created these foreign keys, you can be sure that all the data
stored in your tables will obey the enforced table relationships
...

In Chapter 8, you’ll start learning how to use your new database
...


Diagrams and Table Relationships
Relationships describe how data in one table is linked to data in other tables
...
” Relationships exist for the sole purpose
of associating one table with one or more other tables using primary keys and
foreign keys
...

One-to-one relationships are rarely used, since it’s usually more efficient just to
combine the two records and store them together as columns in a single table
...
In theory, we could store the
phone numbers in a separate table and link to them via a foreign key in the Employees table, but this would be of no benefit to our application, since we assume
that one phone number can belong to only one employee
...


One-to-many Relationships
The one-to-many relationship is by far the most common relationship type
...
These records are usually related on the
basis of the primary key from the first table
...

When a foreign key is used to link two tables, the table that contains the foreign
key is on the “many” side of the relationship, and the table that contains the
primary key is on the “one” side of the relationship
...
In Figure 7
...


288

Diagrams and Table Relationships

Figure 7
...
Database diagram showing a one-to-many
relationship

As you can see, one-to-many relationships are easy to spot if you have a diagram
at hand—just look for the icons next to the tables
...

Select the line that appears between two related tables to view the properties of
the foreign key that defines that relationship
...

As Figure 7
...
24
...
28
...
However, it’s good to have some idea
of the features available through the Properties window, as they may well
come in handy later in your database development career
...
In our application, every user must be associated with a valid department, so we’ll leave this
option enabled
...
If, for some reason,
we changed the ID of a department in the Departments table, we could set the
database to propagate this change to all the tables related to that department,
keeping the relationships intact
...
However, these
are quite sensitive options, and it’s best to avoid them unless you have good
reason not to
...

If these concepts sound a bit advanced at the moment, don’t worry: it will all
become clear as you spend some time working with databases
...

Imagine that you wanted a single employee to be able to belong to more than
one department—someone who works in “Engineering” could also be an “Executive,” for example
...

How do we represent it in our database? Faced with this question, many less-experienced developers begin to think of ways to store several values in a single
column, because the obvious solution is to change the DepartmentID column in

290

Diagrams and Table Relationships

the Employees table so that it contains a list of the IDs of those departments to
which each employee belongs
...

The correct way to represent a many-to-many relationship is to add a third table,
named a mapping table, to the database
...
Figure 7
...


Figure 7
...
Using a mapping table to implement a many-to-many
relationship

The EmployeeDepartment table associates employee IDs with department IDs
...

A mapping table is created in much the same way as any other table
...
Every table we’ve created so far
has had a column named somethingID that was designed to be that table’s primary
key
...
It also speeds up database searches
based on that column
...
Each employee ID may appear more than once, as an employee may belong to more than one department, and each department ID may appear
more than once, as a department may contain many employees
...
For this reason, we usually create mapping tables with a multi-column
primary key
...
This enforces the uniqueness
that is appropriate to a look-up table, and prevents a particular employee from
being assigned to a particular department more than once
...
3

Summary
This chapter has introduced the fundamental concepts of relational databases
...
You’ve also learned
how to implement and enforce table relationships, and you have a solid understanding of good relational database design
...
That language is the
Structured Query Language, or SQL
...
microsoft
...
aspx

8

Speaking SQL

So your database has been created, and you’ve defined all of the tables you’ll
need, all of the columns for your tables—you’ve even defined the relationships
between your tables
...
Mary in Accounting isn’t going to want to download and learn
to use SQL Server Management Studio just so she can retrieve an employee’s
mobile phone number—this functionality has to be provided by the Dorknozzle
intranet web site, which, after all, is supposed to enable staff members to access
data easily
...

SQL has its origins in a language developed by IBM in the 1970s called SEQUEL
(which stood for Structured English QUEry Language), and is still often referred
to as “sequel” or “ess-que-el
...

SQL has roughly 30 keywords and is the language of choice for simple and complex database operations alike
...


Chapter 8: Speaking SQL

SQL is an international standard, and almost all database products, including
SQL Server, Oracle, DB2, and so on, support the standard to a certain degree
...

This chapter cannot begin to cover all there is to know on the subject, but we
hope it will provide you with an introduction to beginning and advanced SQL
concepts
...


Reading Data from a Single Table
Information that’s contained within a database is useless unless we have a way
of extracting it
...
Queries pose questions to the
database server, which returns the answer to your application
...
1
...
1 from the Employees table of the Dorknozzle database
...
Then, in the next chapter, we’ll learn to
access the data from ASP
...

In the following sections, we’ll learn to write queries that will let us view existing
data, insert new data, modify existing data, and delete data
...

Let’s begin: first up, open SQL Server Management Studio
...
Log in to your SQL Server instance, and
select the Dorknozzle database in the Object Explorer pane, as illustrated in Figure 8
...


Figure 8
...
Using SQL Server Management Express

Having selected the Dorknozzle database, go to File > New > Database Engine
Query, or simply click the New Query button on the toolbar
...
2, should open in the right-hand pane
...
2
...
If everything works as planned, the result
will appear similar to Figure 8
...


Figure 8
...
Executing a simple query

Nice work! Now that we’ve taken our first look at SQL, let’s talk more about
SQL queries
...
This query is generally
constructed using a SELECT clause and a FROM clause
...
In this
case, we used *, which means “all columns
...
Together, these two clauses create an
SQL statement that extracts all data from the Departments table
...
If you
wanted to keep the entire statement on one line, that’s fine, but SQL lets you
separate the statements on multiple lines to make complex queries easier to read
...

To sum up, here’s the basic syntax used in a SELECT query:
SELECT

This keyword indicates that we want to retrieve data, rather than modify,
add, or delete data—these activities use the UPDATE, INSERT, and DELETE
keywords, respectively, in place of SELECT
...
We can list multiple columns by separating the column names with commas, or we can use * to select all columns
...
Name, Employees
...
Name

This approach is mandatory when two or more of the tables we’re dealing
with contain columns that have the same names
...


297

Chapter 8: Speaking SQL

FROM

The FROM keyword ends the SELECT clause and starts the FROM clause, which
identifies the tables from which the data will be extracted
...

tables
We need to identify the names of the tables from which we want to extract
data
...
Querying
multiple tables is called a table join—we’ll cover this a bit later
...
4
...
4
...


The Number of Affected Rows
As you can see in Figure 8
...
This report doesn’t indicate that those
records were modified
...


298

Selecting Certain Fields

Viewing Results in Text Format
By default, the query editor of SQL Server Management Studio displays the
results in a grid like the one shown in Figure 8
...
As you work with SQL
Server, you may start to find this view a little impractical; in particular, it
makes viewing longer strings of text painful because each time you run the
query, you need to resize the columns in the grid
...
4
...


Let’s move on and take a look at some variations of the SELECT query
...


Selecting Certain Fields
If you didn’t want to select all the fields from the database table, you’d include
the names of the specific fields that you wanted in place of the * in your query
...
Rather than
specifying the *, which would return all the fields within the database table, we
specify only the fields that we need
...
Moreover,
even when you need all the columns in a table, it’s better to specify them by
name, to safeguard against the possibility that future changes, which cause
more columns to be added to the table, affecting the queries you’re writing
now
...
Take this query, for example:
SELECT DepartmentID, Department
FROM Departments

You could reverse the order in which the columns are returned with this query:

299

Chapter 8: Speaking SQL

SELECT Department, DepartmentID
FROM Departments

Executing this query would produce the result set shown in Figure 8
...


Figure 8
...
Retrieving department names and their IDs

Try it for yourself!

Selecting Unique Data with DISTINCT
Say you want to find out which cities your employees hail from
...

Figure 8
...

That’s not usually what we want to see in our results
...

Adding the DISTINCT keyword immediately after the SELECT clause extracts only

300

Selecting Unique Data with DISTINCT

Figure 8
...
Reading the employees’ cities

the unique instances of the retrieved data
...
7
...
7
...

Note that the uniqueness condition applies to the whole of the returned rows
...
To see for yourself, execute this
query:
SELECT DISTINCT Name, City
FROM Employees

The results of this code are pictured in Figure 8
...
As we expected, the DISTINCT
clause doesn’t have any effect, since each row is unique
...
8
...

The following example could be used to extract all employees that work in the
Department whose ID is 6:
SELECT Name, DepartmentID
FROM Employees
WHERE DepartmentID = 6

This query returns the results shown below:
Name
-------------------------------------------------Ted Lindsey
Shane Weebe

302

DepartmentID
-----------6
6

Selecting Ranges of Values with BETWEEN

(2 row(s) affected)

But wait! How do I know the name of the department with the ID of 6? Well,
you could use a similar query to find out
...

Department
-------------------------------------------------Engineering
(1 row(s) affected)

Selecting Ranges of Values with BETWEEN
There may be times when you’ll want to search within a database table for rows
that fall within a certain range of values
...

Note that the range is inclusive, so departments with IDs of 2 and 5 will also be
retrieved
...


Matching Patterns with LIKE
As we’ve just seen, the WHERE clause allows us to filter results based on criteria
that we specify
...
For example, if we wanted
to search the company’s Employees table for all employees named Zak Ruvalcaba,
we'd use the following SQL statement:
SELECT EmployeeID, Username
FROM Employees
WHERE Name = 'Zak Ruvalcaba'

However, we won’t see many such queries in reality
...
When an arbitrary string such as a name is used (as in the example above),
it’s likely that we’re searching for data based on partially complete information
...
The LIKE keyword allows us to perform pattern matching
with the help of wildcard characters
...

If we wanted to find all names within our Employees table with the surname of
Ruvalcaba, we could modify the SQL query using a wildcard, as follows:
SELECT EmployeeID, Name
FROM Employees
WHERE Name LIKE '%Ruvalcaba'

With this query, all records in which the Name column ends with Ruvalcaba are
returned, as shown below
...
But what would happen if we didn’t know
how to spell the entire last name? That name is pretty difficult to spell! You could
solve the problem by modifying your SQL statement to use two wildcards as
follows:
SELECT EmployeeID, Name
FROM Employees
WHERE Name LIKE '%Ruv%'

In this case, the wildcard is placed before and after the string Ruv
...
As SQL is case-insensitive, this would include the names Sarah Ruvin, Jonny
Noruvitch, Truvor MacDonald, and so on
...
Let’s say we want to find all employees
who live in California, Indiana, and Maryland
...
Since our database only
contains employees living in CA, only those records will be displayed
...
We’ll most likely receive the results sorted by
the primary key, because it’s easier for SQL Server to present the results in this
way than any other, but this ordering isn’t guaranteed
...
The ORDER BY clause
provides you with a quick way to sort the results of your query in either ascending
or descending order
...
e
...
You
could add the DESC designation (for descending) to the end of the statement, to
order the results backwards:
SELECT EmployeeID, Name
FROM Employees
ORDER BY Name DESC

306

Limiting the Number of Results with TOP

If you execute this query, you’ll get the results we saw above, listed in reverse
order
...
e
...


Limiting the Number of Results with TOP
Another using SQL keyword is TOP, which can be used together with SELECT to
limit the number of returned rows
...
Yet in
many real-world applications, you’ll need to extract data from multiple tables
simultaneously
...

Let’s learn about joins and subqueries by looking closely at a typical example
...
To find employee data, you’d normally query the Employees
table, and apply a WHERE filter on the ID of the department
...
Using this data, you can make a new query to find the employees in that de-

partment:
SELECT Name
FROM Employees
WHERE DepartmentID = 6

This query retrieves the same list of employees we saw earlier in this chapter
...
You could use either subqueries or
joins to do the job, so let’s take a look at them in turn
...
For example, you could retrieve all the employees
who work in the Engineering department like this:
SELECT Name
FROM Employees
WHERE DepartmentID IN
(SELECT DepartmentID
FROM Departments
WHERE Department LIKE '%Engineering')

In this case, the subquery (highlighted in bold) returns the ID of the Engineering
department, which is then used to identify the employees who work in that department
...


308

Table Joins

Note that we’re using the IN operator instead of the equality operator (=)
...
For example, if we added
another department with the name “Product Engineering,” or accidentally added
another Engineering record to the Departments table, our subquery would return
two IDs
...


Querying Multiple Tables
When using queries that involve multiple tables, it’s useful to take a look at
the database diagram you created in Chapter 7 to see what columns exist in
each table, and to get an idea of the relationships between the tables
...
In Chapter 7, we created such a relationship
between the Employees table and the Departments table using a foreign key
...
Name
FROM Departments
INNER JOIN Employees ON Departments
...
DepartmentID
WHERE Departments
...
We use Employees
...
DepartmentID
instead of DepartmentID
...
Name), adding the name of the table is
optional
...
John
Smith works in the same department as you, and his desk is just across the aisle
...
When addressing a large group of colleagues, you would use John Smith’s
full name, otherwise people could become confused
...
In exactly the same way,
you could always refer to a column in a database using the Table
...

As for the join itself, the code is fairly clear: we’re joining the Departments table
and the Employees table into a single, virtual table by matching the values in the
Departments
...
DepartmentID
column
...
Department LIKE '%Engineering'
...
Try this query:
SELECT Employees
...
Department
FROM Departments
INNER JOIN Employees ON Departments
...
DepartmentID

The results are as you’d expect:
Name
-------------------------------Zak Ruvalcaba
Jessica Ruvalcaba
Ted Lindsey
Shane Weebe
David Levinson
Geoff Kim

Department
--------------------------------Executive
Marketing
Engineering
Engineering
Marketing
Accounting

(6 row(s) affected)

Expressions and Operators
In the wonderful world of programming, an expression is any piece of code that,
once evaluated, results in a value
...

In SQL, expressions work in much the same way, though they don’t necessarily
have to be mathematical
...
Try this query:
SELECT EmployeeID, Name + ', ' + City AS NameAndCity
FROM Employees

310

Expressions and Operators

The results are shown below:
EmployeeID
---------1
2
3
4
5
6

NameAndCity
------------------------------------------------------Zak Ruvalcaba, San Diego
Jessica Ruvalcaba, San Diego
Ted Lindsey, San Diego
Shane Weebe, San Diego
David Levinson, San Diego
Geoff Kim, San Diego

(6 row(s) affected)

Note that the results of the expression are used to create a virtual column
...

We give this column the name NameAndCity using the AS keyword
...
Over the course
of the previous sections, you’ve seen the operators =, AND, >=, <=, LIKE and IN at
work
...

+

The addition operator adds two numbers or combines two strings
...

*

The multiplication operator multiplies one number with another
...

>

The greater-than operator is used in WHERE clauses to determine whether the
first value is greater than the second
...
e
...

SELECT Name
FROM Employees
WHERE EmployeeID > 10

311

Chapter 8: Speaking SQL

<

The less-than operator is used in WHERE clauses to determine whether the
first value is less than the second
...
e
...

SELECT Name
FROM Employees
WHERE EmployeeID < 10
>=

The greater-than or equal-to operator is used in WHERE clauses to determine
whether the first value is greater than, or equal to, the second
...

SELECT Name
FROM Employees
WHERE EmployeeID >= 10
<=

The less-than or equal-to operator is used in WHERE clauses to determine
whether the first value is less than, or equal to, the second
...

SELECT Name
FROM Employees
WHERE EmployeeID <= 10
<>, !=

This operator is used to check whether a value is not equal to a second
...
The OR
operator can be used when a certain condition needs to be met, or when only
one of two conditions needs to be met
...

SELECT Name
FROM Employees
WHERE EmployeeID = 1 OR EmployeeID = 2

312

Transact-SQL Functions

AND

This operator works just like OR, except that it requires all of the conditions
to be satisfied, not just any of them
...
For
example, the following query would return all employees whose name does
not begin with “Jess
...
For instance, if you weren’t sure of the first
letter of Geoff Kim’s surname, you could use the following query:
SELECT Name
FROM Employees
WHERE Name LIKE 'Geoff _im'

This would return Geoff Kim’s record, as well as Geoff Sim’s, Geoff Lim’s,
and so on, were there such employees in the database
...

To match zero or more characters, you’d use the % or * operator
...

IN

This operator is used in WHERE clauses to specify that an expression’s value
must be one of the values specified in a list
...
For the most part,
SQL has sufficient functions to handle almost all of the day-to-day tasks that

313

Chapter 8: Speaking SQL

you’ll undertake
...


Getting More Information
Note that the complete list of built-in functions supported by T-SQL is much
longer than that presented here; you can find the complete lists by searching
for, say, “string functions” or “date and time functions” in the free SQL
Server documentation, SQL Server Books Online, which can be downloaded
from Microsoft’s TechNet site
...
However, this is an advanced topic that we won’t be covering in
this book
...
Although the commonly-preferred
solution is to perform such calculations in VB or C# code, SQL’s arithmetic
functions can prove handy at times
...
Both of the following queries will
return the value 5:
SELECT ABS(5)
SELECT ABS(-5)
CEILING
CEILING returns the smallest integer that’s greater than the value that was

passed in
...
The
following query will return 6:
SELECT CEILING(5
...

The following query will return the value 5:
SELECT FLOOR(5
...
microsoft
...
mspx

String Functions

MOD
MOD returns the remainder of one value divided by another
...

POWER

This function returns the result of one value raised to the power of another
...


Many, many more mathematical functions are available—check SQL Server
Books Online for a full list
...

UPPER, LOWER

This function returns the value passed in as all uppercase or all lowercase,
respectively
...

LTRIM, RTRIM

This function trims whitespace characters, such as spaces, from the left- or
right-hand side of the string, respectively
...

SELECT REPLACE('I like chocolate', 'like', 'love')

315

Chapter 8: Speaking SQL

This query will search the string “I like chocolate” for the word “like” and
replace it with the word “love,” as shown in the output below:
-----------------------------------------------------I love chocolate
(1 row(s) affected)
SUBSTRING

This function returns the sequence of characters within a given value, beginning at a specified start position and spanning a specified number of characters
...
Thus, the following query would
return a list of all usernames, and how many characters were in each username:
SELECT Username, LEN(Username) AS UsernameLength
FROM Employees
CHARINDEX

This function returns the first position in which a substring can be found in
a string
...
For example, the following SQL
query would return the first name of every employee within the Employees table:
SELECT SUBSTRING(Name, 1, CHARINDEX(' ', Name)) AS FirstName
FROM Employees

Here, we’re using two string functions
...
If we assume that the first space indicates the end of
the first name, we can then use SUBSTRING to extract the first name from the
name string
...
9, are as we expect
...
9
...

If an employee had no spaces in his or her name (imagine, for instance, that we
hired Cher to work as an Engineer), then the CHARINDEX function would return
-1, indicating that there was no space character in the name
...


Date and Time Functions
Date and time functions facilitate the manipulation of dates and times that are
stored within your database
...
Here are some of the most useful ones:
GETDATE

returns the current date and time

317

Chapter 8: Speaking SQL

DATEADD

adds an interval to an existing date (a number of days, weeks, etc
...
Here’s a quick example that displays the current
year:
SELECT YEAR(GETDATE())

The result (assuming it’s still 2006, of course) is shown below:
CurrentYear
----------2006
(1 row(s) affected)

Working with Groups of Values
Transact-SQL includes two very useful clauses that handle the grouping of records,
and the filtering of these groups: GROUP BY and HAVING
...


318

The COUNT Function

When working with groups of data, you’ll usually need to use aggregate functions
...
Aggregate functions, on the other hand, can handle
a variable number of parameters, and can perform a range of tasks with these
parameters
...
In the following
pages, we’ll learn about the GROUP BY and HAVING clauses, which are useful when
working with aggregate functions; we’ll also explore the COUNT, SUM, AVG, MIN and
MAX functions
...
If you
wanted to retrieve the total count of employees in your Employees table, you
could run the following query:
SELECT COUNT(Name) AS NumberOfEmployees
FROM Employees

Running this query with your current sample data would return the number of
employees stored in the database, as follows:
NumberOfEmployees
----------------6
(1 row(s) affected)

The COUNT function becomes far more useful when combined with a GROUP BY
clause
...
We already know how to get a list of employees and their departments:
SELECT Departments
...
Name
FROM Employees
INNER JOIN Departments ON Departments
...
DepartmentID

319

Chapter 8: Speaking SQL

The results of this query are shown below:
Department
-------------------------------Executive
Marketing
Engineering
Engineering
Marketing
Accounting

Name
-------------------------------Zak Ruvalcaba
Jessica Ruvalcaba
Ted Lindsey
Shane Weebe
David Levinson
Geoff Kim

(6 row(s) affected)

Now, let’s build on this query to find out how many employees work in each
department
...
Department, COUNT(Employees
...
DepartmentID =
Employees
...
Department' is invalid in the select list
because it is not contained in either an aggregate function or the
GROUP BY clause
...

It knows that we want to count employees, but it doesn’t understand how the
Department
...
We can tell SQL Server to count
the employees based on their departments by adding a GROUP BY clause, like
so:
SELECT Departments
...
Name) AS
HowManyEmployees
FROM Employees
INNER JOIN Departments ON Departments
...
DepartmentID
GROUP BY Departments
...
We can filter out those employees using a WHERE clause,
as shown below:
SELECT Departments
...
Name) AS
HowManyEmployees
FROM Employees
INNER JOIN Departments ON Departments
...
DepartmentID
WHERE Employees
...
Department

While this query is a little complicated, the WHERE clause by itself is pretty
simple—it includes only employees with names that end with Ruvalcaba
...
The HAVING clause
works similarly to the WHERE clause, except that it removes records after the aggregate functions have been applied
...
It seeks to find out which of the departments listed in the Dorknozzle
database have at least two employees
...
Department, COUNT(Employees
...
DepartmentID =
Employees
...
Department
HAVING COUNT(Employees
...

AVG

The AVG function receives a list of numbers as its arguments, and returns the
average of these numbers
...

These functions are great for the statistical analysis of records within the database
...


Updating Existing Data
Okay, so SQL is so great for querying existing data! But how are we supposed to
add data to the tables in the first place? We can’t exactly ask Dorknozzle employees to add data to our tables using SQL Server Management Studio, can we? We

322

The INSERT Statement

need to learn how to add, update, and delete data inside our database programatically
...
Let’s put them to work!

The INSERT Statement
Here's a very simple example of INSERT in action:
INSERT INTO Departments (Department)
VALUES ('Cool New Department')

Executing this command adds a new department, named Cool New Department,
to our database
...

If, in Chapter 7, you used the database scripts to create database structures and
insert data, you probably noticed that the script contained many INSERT commands; these populated the tables with the sample data
...
The INTO part is optional, but it can make your commands easier
to read
...

column names
We also list the names of the columns for which we’ll be supplying data in
this statement
...

VALUES

This keyword comes between the list of columns and their values
...


323

Chapter 8: Speaking SQL

Try the above SQL statement
...


Identity Values
To obtain programatically the identity value that we just generated, we can
use the scope_identity function like this:
SELECT scope_identity()

The UPDATE Statement
We use the UPDATE statement to make changes to existing records within our
database tables
...
Consider this code:
UPDATE Employees
SET Name = 'Zak Christian Ruvalcaba'
WHERE EmployeeID = 1

This statement would change the name of the employee whose EmployeeID is 1
...

table name
We give the name of the table we’re updating
...

column names and values
We provide a list of column names and values, separated by commas
...


Updating Records
Be sure always to include a WHERE clause in your UPDATE statement! If you
fail to do so, all the records will be updated, which is not usually what you
want!

The DELETE Statement
The DELETE statement removes records from the database
...

In case you’re curious, here’s the error message that would be generated by the
previous DELETE command:
Msg 547, Level 16, State 0, Line 1
The DELETE statement conflicted with the REFERENCE constraint
"FK_Employees_Departments"
...
Employees", column 'DepartmentID'
...


You could just as easily delete that new department you created earlier:
DELETE
FROM Departments
WHERE Department = 'Cool New Department'

Real-world References
Remember that in real-world scenarios, items should be referenced by their
IDs, not by name (as is shown in the example above)
...


325

Chapter 8: Speaking SQL

The command above would execute successfully because there aren’t any employees linked to the new department
...

Much like VB or C# functions, stored procedures can take parameters and return
values
...
For example, let’s say that you want to add to your web site functionality
that allows departments to be deleted
...

To help with such management issues, you could have a stored procedure that
copies the employees of that department to another table (called EmployeesBackup), deletes those employees from the main Employees table, then removes
the department from the Department table
...

We’ll see a more realistic example of a stored procedure in the next chapter, when
we start to add more features to the Dorknozzle project, but until then, let’s learn
how to create a stored procedure in SQL Server, and how to execute it
...
The parameter names, as well the names of
variables we can declare inside stored procedures, start with @
...

The stored procedure shown below creates a new department whose name is
specified through the first parameter
...
Now,
such a stored procedure wouldn’t make much sense in reality, but this example
allows you to learn a few interesting details that you’ll be using frequently as you
develop applications, and it uses much of the theory you’ve learned in this chapter
...
Department, Employees
...
DepartmentID =
Employees
...
You can now execute your new stored procedure by supplying the required parameters as follows:
EXECUTE DoThings 'Research', 'Cristian Darie', 'cristian'

If you execute the procedure multiple times, you’ll get the same results, since any
data that’s created as part of the stored procedure is deleted at the end of the
stored procedure
...

The beginning of the stored procedure code specifies its name and its parameters:
CREATE PROCEDURE DoThings
(
@NewDepartmentName VARCHAR(50),
@NewEmployeeName VARCHAR(50),
@NewEmployeeUsername VARCHAR(50)
)
AS

The parameters include a department name, an employee name, and an employee
username
...
Feel free to play with your existing
procedure, to get a feel for how this works
...
This value is
returned by the scope_identity function, which returns the most recently generated identity value
...
The value
is saved into a new variable named @NewDepartmentID
...

The stored procedure continues by creating a new employee using the name and
username it received as parameters; it assigns this employee to the department
that was created earlier:
-- Create a new employee
INSERT INTO Employees (DepartmentID, Name, Username)
VALUES (@NewDepartmentID, @NewEmployeeName, @NewEmployeeUsername)

Again, right after creating the new employee, we store its ID into a variable named
@NewEmployeeID
...

-- Obtain the ID of the created employee
DECLARE @NewEmployeeID INT
SET @NewEmployeeID = scope_identity()

329

Chapter 8: Speaking SQL

Finally, with the new department and employee in place, the stored procedure
selects the list of departments together with their employees:
-- List the departments together with their employees
SELECT Departments
...
Name
FROM Departments
INNER JOIN Employees ON Departments
...
DepartmentID

For the purposes of this example, we’d prefer to keep the database tidy, which
is why we’re deleting the new records at the end of the stored procedure
...
SQL also allows for
some of the other programming constructs we’ve seen in this book, such as If
statements, While loops, and so on, but advanced stored procedure programming
is a little beyond the scope of this book
...
As you have seen, SQL not only returns simple results from
individual tables, but can produce complex data queries complete with filtering,
sorting, expressions, and even nested statements
...
In Chapter 9, you’ll begin to use the
knowledge you’ve gained about databases, and the language that connects those
databases together, to create a real, working application
...
NET

Through the preceding chapters, you’ve made major strides into the world of
dynamic web development using ASP
...
You’ve learned about interface development using web forms and web controls, you’ve learned about modeling and
structuring your data within the framework of a database—you’ve even learned
about the SQL language that’s used to access the data stored within your database
...

The next step is to learn how to access a database using VB or C# code
...
NET
...

ADO
...
NET) is a modern Microsoft technology that
permits us to access a relational database from an application’s code
...
NET, we’ll be able to display lists of employees and departments, and allow
users to add data to the data store, directly from the Dorknozzle application
...
NET

Chapter 9: ADO
...
NET
❑ how to display data that is read from a database
❑ how to handle data access errors

Introducing ADO
...
Now,
it’s time to apply this knowledge
...
NET’s classes to connect to the database; we’ll then use that connection
to execute SQL queries
...
NET 2
...
NET is able to use different types of data connections, depending on
the kind of database to which the application is trying to connect
...
NET classes whose names start with Sql (such as the previously
mentioned SqlConnection, SqlCommand, etc
...

Similar classes are provided for other databases—for example, if you’re
working with Oracle, you can use classes such as OracleConnection,
OracleCommand, and so on
...

In this book, we’ll use only the Sql classes, but it’s good to know that you
have options!

In order to use ADO
...

Since we’re using SQL Server, you’ll need to import the System
...
SqlClient
namespace
...


332

Importing the SqlClient Namespace

SqlCommand

This class holds data about the SQL queries and stored procedures that you
intend to run on your SQL Server database
...
This class
comes with properties and methods that let you iterate through the data it
contains
...

The System
...
SqlClient namespace exposes many more than the few classes
listed above
...

Once you’re ready to begin working with ADO
...


Import the necessary namespaces
...


Define a connection to your database with an SqlConnection object
...


When you’re ready to manipulate your database, set up the appropriate
query in an SqlCommand object
...


Open the connection and execute the SQL query to return the results into
a SqlDataReader object
...


Extract relevant database data from the SqlDataReader object and display
it on your web page
...


Close the database connection
...


Importing the SqlClient Namespace
It’s been a while since we’ve written some VB or C# code! Let’s fire up our old
friend, Visual Web Developer, and load the Learning project
...


333

Chapter 9: ADO
...

Select the Web Form template, and name it AccessingData
...
Uncheck the
Place code in separate file and Select master page checkboxes, as shown in Figure 9
...


Figure 9
...
Creating the AccessingData
...
aspx (excerpt)

<%@ Page Language="VB" %>
<%@ Import Namespace = "System
...
SqlClient" %>
...
w3
...
dtd">

Defining the Database Connection
With our import of the SqlClient namespace complete, we can create a new
instance of the SqlConnection, which will facilitate our connection to the database
...
A typical connection string for a SQL Server
Express database looks like this:
Server=computer\SqlExpress;Database=database;User ID=username;
Password=password
The connection string must specify the name of the computer on which the
database is located (you can always use localhost to refer to the local machine)
and the name assigned to the database server instance (SqlExpress is the default
for SQL Server Express)
...

SQL Server supports two methods of authentication: SQL Server Authentication
and Windows Authentication
...
To tell SQL Server that we’re logging
in using Windows Authentication, our connection string would include Integrated Security=True, rather than a username and password, as shown here:
Server=computer\SqlExpress;Database=database;Integrated Security=True

SQL Server Authentication
Be aware that, when the ASP
...
NET
through IIS, it authenticates to SQL Server using a special account named
ASPNET
...


Let’s put this into practice by creating an SqlConnection in the Page_Load event
handler
...
This should take you back to Source View where you can see the Page_Load
method that was created for you
...
aspx (excerpt)

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
NET

If you get sick of typing quotes, ampersands, and underscores, you can combine
the three bold strings in the above code into a single string
...
aspx (excerpt)

protected void Page_Load(object sender, EventArgs e)
{
// Define database connection
SqlConnection conn = new SqlConnection(
"Server=localhost\\SqlExpress;Database=Dorknozzle;" +
"Integrated Security=True");
}

Be aware that, in C#, the backslash (\) character has a special meaning when it
appears inside a string, so, when we wish to use one, we have to use the double
backslash (\\) shown above
...
The SqlCommand object accepts two parameters: the first is the
SQL statement, and the second is the connection object that we created in the
previous step
...
aspx (excerpt)

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
aspx (excerpt)

protected void Page_Load(object sender, EventArgs e)
{
// Define database connection
SqlConnection conn = new SqlConnection(
"Server=localhost\\SqlExpress;Database=Dorknozzle;" +

336

Executing the Command

"Integrated Security=True");
// Create command
SqlCommand comm = new SqlCommand(
"SELECT EmployeeID, Name FROM Employees", conn);
}

Executing the Command
When we’re ready to run the query, we open the connection and execute the
command
...
The three methods are as follows:
ExecuteReader
ExecuteReader is used for queries or stored procedures that return one or
more rows of data
...
Using the SqlDataReader object is the fastest way to retrieve records from the database, but it can’t be used to update the data or
to access the results in random order
...
This can be a problem, as the database server will usually
have a limited number of connections—people who are using your application
simultaneously may start to see errors if you leave these connections open
...
You’ll learn more about the
DataTable object in Chapter 12
...
This method returns an Object, which you can convert to specific
data types depending on the kinds of data you expect to receive
...
The return
value will be the number of affected rows
...
NET

As we’re reading a list of employees, we’ll be using ExecuteReader
...

Visual Basic

File: AccessingData
...
EventArgs)
' Define database connection
Dim conn As New SqlConnection("Server=localhost\SqlExpress;" & _
"Database=Dorknozzle;Integrated Security=True")
' Create command
Dim comm As New SqlCommand( _
"SELECT EmployeeID, Name FROM Employees", conn)
' Open connection
conn
...
ExecuteReader()
' TODO: Do something with the data
' Close the reader and the connection
reader
...
Close()
End Sub
C#

File: AccessingData
...
Open();
// Execute the command
SqlDataReader reader = comm
...
Close();
conn
...
Before
we can query our database, a connection must be opened, so we need to call the
Open method of our SqlConnection object conn
...
ExecuteCommand will retrieve a list of all employees and return the list in
an open SqlDataReader object
...

Immediately after we’ve done something with the data, we close our
SqlDataReader and SqlConnection objects using their Close methods
...
As such, it’s best practice to keep
the connection open for the minimum time
...


Setting up Database Authentication
If you’re running your ASP
...
aspx
...

Provided everything else is as it should be, the error will look like the one shown
in Figure 9
...
3
if you run the code with debugging using Visual Web Developer
...
In the background, every time
your code requests a system resource, Windows checks to make sure that you
have access to that resource
...
Windows also checks to make
sure that you have access to the database
...
NET

Figure 9
...
A database connection error trapped by the ASP
...
3
...

When you run Dorknozzle through IIS, on the other hand, the code is executed
as if it were being run by a special user called ASPNET (or Network Service in
Windows Server 2003)
...
Let’s do that now
...
Click the New Query button to open a new query window
...

-- Add the ASPNET account to SQL Server
EXEC sp_grantlogin 'MachineName\ASPNET'
-- Give the ASPNET account access to Dorknozzle
USE Dorknozzle
EXEC sp_grantdbaccess 'MachineName\ASPNET'
-- Give the ASPNET account full privileges to Dorknozzle
EXEC sp_addrolemember 'db_owner', 'MachineName\ASPNET'

What’s the Name of my Machine?
If you’re not sure of the name of your machine, right-click on My Computer,
which you can find either on the desktop or in the Start menu, and select
Properties
...


Now, when you’re running the application through IIS, you can connect to SQL
Server from your web application using Integrated Windows Authentication
...
aspx; this time, you shouldn’t see any connectivity errors
...
This is the connection mode you’ll most likely use when connecting to remote SQL Server
instances using the username and password provided to you by that database’s
administrator
...
Replace

341

Chapter 9: ADO
...

Visual Basic

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 you’ve opened the connection and executed the command
...
To do this, we’ll simply use a While loop to add the data to a Label
control that we’ll place in the form
...
aspx web form
...
NET
...
aspx (excerpt)



Using ADO<br> ...<br> <br />Visual Basic<br /><br />File: AccessingData<br> ...<br> Open()<br />' Execute the command<br />Dim reader As SqlDataReader = comm<br> ...<br> Read()<br />employeesLabel<br> ...<br> Item("Name") & "<br />"<br />End While<br />' Close the reader and the connection<br />reader<br> ...<br> Close()<br />C#<br /><br />File: AccessingData<br> ...<br> Open();<br />// Execute the command<br />SqlDataReader reader = comm<br> ...<br> Read())<br />{<br />employeesLabel<br> ...<br> Close();<br />conn<br> ...<br> 4<br> ...<br> NET<br /><br />We already know that the SqlDataReader class reads the data row by row, in a<br />forward-only fashion<br> ...<br> When we call<br />reader<br> ...<br> <br />If there’s data to be read, it returns True; otherwise—if we’ve already read the<br />last record returned by the query—the Read method returns False<br> ...<br> 4<br> ...<br> <br />SELECT EmployeeID, Name, Username, Password<br />FROM Employees<br />WHERE EmployeeID = EmployeeID<br /><br />Let’s build a page like the one shown in Figure 9<br> ...<br> <br /><br />Figure 9<br> ...<br> Retrieving details of a specific employee<br /><br />Create a new web form called QueryParameters<br> ...<br> aspx (excerpt)<br /><br /><%@ Page Language="VB" %><br /><%@ Import Namespace="System<br> ...<br> SqlClient" %><br /><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1<br> ...<br> w3<br> ...<br> dtd"><br /><br />344<br /><br /> Using Parameters with Queries<br /><br /><script runat="server"><br /></script><br /><html xmlns="http://www<br> ...<br> org/1999/xhtml" ><br /><head runat="server"><br /><title>Using Query Parameters




User ID:

Text="Get Data" />







With these amendments, we’ve added a Textbox control into which users can
type in the ID of the employee whose information they want to see
...

Next, we need to add a Click event handler to the Button control
...


Read the ID typed by the user in the idTextBox control
...


Prepare an SQL query to retrieve data about the specified employee
...


Execute the query and read the results
...
Text , conn)

If the user entered the number 5 into the text box and clicked the button, the
following query would be run:
SELECT EmplyeeID, Name, Username, Password
FROM Employees
WHERE EmployeeID = 5

345

Chapter 9: ADO
...
However, if—as is perhaps more likely—the user entered an
employee’s name, your application would attempt to run the following query:
SELECT EmployeeID, Name, Username, Password
FROM Employees
WHERE EmployeeID = Zac Ruvalcaba

This query would cause an error in the database, which would, in turn, cause an
exception in your web form
...
NET
allows you to define parameters in your query, and to give each of those parameters a type
...
To do so, we
add the @ symbol, followed by an identifier for our parameter (in this case, we’ve
used EmployeeID)
...
Parameters
...
Data
...
Int)
comm
...
Value = idTextBox
...
Parameters
...
Data
...
Int);
comm
...
Value = idTextBox
...
Parameters, passing in the name of the
parameter (EmployeeID) and the parameter’s type; we’ve told ADO
...

One of the most common SQL Server data types is nvarchar
...
Parameters
...
SqlDbType
...
Parameters("@Username")
...
Parameters
...
NVarChar, 50);
comm
...
Value = username;

Notice that we’ve included an additional parameter in our call to the Add method
...
We’ve given the Username field in our Employees table a maximum size of 50 characters, so our code should reflect this
...
Parameters
...
Data
...
NET Framework’s
SDK Documentation
...
aspx
...
Next,
fill the event handler with the code shown below:
Visual Basic

File: QueryParameters
...
EventArgs)
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
' Initialize connection
conn = New SqlConnection("Server=localhost\SqlExpress;" & _
"Database=Dorknozzle;Integrated Security=True")
' Create command
comm = New SqlCommand( _
"SELECT EmployeeID, Name, Username, Password " & _
"FROM Employees WHERE EmployeeID=@EmployeeID", conn)
' Verify if the ID entered by the visitor is numeric
Dim employeeID As Integer
If (Not Integer
...
Text, employeeID)) Then
' If the user didn't enter numeric ID
...
Text = "Please enter a numeric ID!"
Else
' Add parameter
comm
...
Add("@EmployeeID", System
...
SqlDbType
...
Parameters("@EmployeeID")
...
Open()
' Execute the command
reader = comm
...
NET

If reader
...
Text = "Employee ID: " & _
reader
...
Item("Name") & "
" & _
"Username: " & reader
...
Item("Password")
Else
userLabel
...
Close()
conn
...
aspx (excerpt)

protected void submitButton_Click(object sender, EventArgs e)
{
// Declare objects
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
// Initialize connection
conn = new SqlConnection("Server=localhost\\SqlExpress;" +
"Database=Dorknozzle;Integrated Security=True");
// Create command
comm = new SqlCommand(
"SELECT EmployeeID, Name, Username, Password " +
"FROM Employees WHERE EmployeeID=@EmployeeID", conn);
// Verify if the ID entered by the visitor is numeric
int employeeID;
if (!int
...
Text, out employeeID))
{
// If the user didn't enter numeric ID
...
Text = "Please enter a numeric ID!";
}
else
{
// Add parameter
comm
...
Add("@EmployeeID", System
...
SqlDbType
...
Parameters["@EmployeeID"]
...
Open();
// Execute the command
reader = comm
...
Read())
{
userLabel
...
Text =
"There is no user with this ID: " + employeeID;
}
// Close the reader and the connection
reader
...
Close();
}
}

Now, when the user clicks the button, the Click event is raised, and the event
handler is executed
...
This check
can be done with the Integer
...
TryParse
method in C#:
Visual Basic

File: QueryParameters
...
TryParse(idTextBox
...
aspx (excerpt)

// Verify if the ID entered by the visitor is numeric
int employeeID;
if (!int
...
Text, out employeeID))
{


This method verifies whether or not the string we pass as the first parameter can
be cast to an integer, and if yes, the integer is returned through the second parameter
...
Out parameters are parameters
that are used to retrieve data from a function, rather than send data to that
function
...
NET

of them can exist for any method
...

If the ID that’s entered isn’t a valid number, we notify the user, as Figure 9
...


Figure 9
...
Invalid input data generating a warning

We also notify the user if the query doesn’t return any results
...
Read only returns True if the query returns
a record
...
aspx (excerpt)

' Display the requested data
If reader
...
Text = "Employee ID: " & reader
...
aspx (excerpt)

// Display the requested data
if (reader
...
Text = "Employee ID: " + reader["EmployeeID"] +


Figure 9
...

There are still a couple of details that we could improve in this system
...
Let’s
look at this problem next
...
7
...
aspx seems to be perfect, right? Well,
not quite
...
It’s very good practice to enclose such code in Try-Catch-Finally
blocks, and always to use the Finally block to close any open data objects
...

Take a look at the following code samples
...
aspx (excerpt)

Protected Sub submitButton_Click(ByVal sender As Object, _
ByVal e As System
...
TryParse(idTextBox
...


351

Chapter 9: ADO
...
Text = "Please enter a numeric ID!"
Else
' Add parameter
comm
...
Add("@EmployeeID", System
...
SqlDbType
...
Parameters("@EmployeeID")
...
Open()
' Execute the command
reader = comm
...
Read() Then
userLabel
...
Item("EmployeeID") & "
" & _
"Name: " & reader
...
Item("Username") & "
" & _
"Password: " & reader
...
Text = _
"There is no user with this ID: " & employeeID
End If
reader
...
Text = "Error retrieving user data
...
Close()
End Try
End If
End Sub
C#

File: QueryParameters
...
TryParse(idTextBox
...

userLabel
...
Parameters
...
Data
...
Int);
comm
...
Value = employeeID;
// Enclose database code in Try-Catch-Finally
try
{
// Open the connection
conn
...
ExecuteReader();
// Display the requested data
if (reader
...
Text = "Employee ID: " +
reader["EmployeeID"] + "
" +
"Name: " + reader["Name"] + "
" +
"Username: " + reader["Username"] + "
" +
"Password: " + reader["Password"];
}
else
{
userLabel
...
Close();
}
catch
{
// Display error message
userLabel
...
";
}
finally
{
// Close the connection
conn
...
NET

}
}
}

So, what’s new in this version of the event handler, apart from the fact that it’s
become larger? First of all—and most important—we have the Try-Catch-Finally
block in place
...
If
an error arises, we display a message for the user through the Catch block
...


Using the Repeater Control
The
...
These controls allow you to easily format database data within
an ASP
...

In this chapter, you’ll learn how to work with the Repeater; we’ll cover the other
controls in the next few chapters
...
NET, but we’re presenting them together with ADO
...


Where’s the DataGrid?
ASP
...
0 and ASP
...
1 developers may wonder what happened to
the DataGrid control, which used to be the control of choice for displaying
grids of data
...
NET 2
...
Unless you
need to maintain older applications, the GridView control should be used
...
NET control that allows the easy
presentation of data directly from a data source, usually in just a handful of lines
of code
...
microsoft
...
The difference with this control is that it has an
subtag—otherwise known as a child tag—located within the
main tag, or parent tag
...
However, before this data can be displayed, we have to bind an
SqlDataReader object (which contains the results of an SQL query) to the
Repeater control using the process known as data binding
...
DataSource = reader
myRepeater
...
First, let’s discuss what’s happening here in more detail
...
The markup to be repeated is provided as templates for
the Repeater to use
...
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
...

Each of these templates must be specified in a child tag of the

tag:


This template provides a header for the output
...



The only template that is actually required, specifies the
markup that should be output for each item in the data source
...
NET

generating an HTML table, this template would contain the and
tags and their contents
...



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



This template provides a footer for the resulting output, which will appear
after all the items in the data source
...

Let’s take a look at a repeater control that displays a table of employees
...
aspx in
the Learning application
...
Import
the System
...
SqlClient namespace just as you did for the other two forms
we’ve created in this chapter
...
aspx (excerpt)

<%@ Page Language="VB" %>
<%@ Import Namespace="System
...
SqlClient" %>
...
w3
...
dtd">



Using the Repeater






356

Using the Repeater Control



















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
...

Next, we provide a template for each item in the result set
...
In both VB and
C#, we use Eval to retrieve database values
...
DataItem("FieldName") in VB
...
Eval(Container
...

Finally, here’s the that includes the closing tag
...
Use Visual Web Developer to generate the web form’s Load event handler,
and complete it like this:

357

Chapter 9: ADO
...
aspx (excerpt)

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
Open()
' Execute the command
reader = comm
...
DataSource = reader
myRepeater
...
Close()
Catch
' Display error message
Response
...
")
Finally
' Close the connection
conn
...
aspx (excerpt)

protected void Page_Load(object sender, EventArgs e)
{
// Declare objects
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
// Initialize connection
conn = new SqlConnection("Server=localhost\\SqlExpress;" +
"Database=Dorknozzle;Integrated Security=True");
// Create command
comm = new SqlCommand(

358

Using the Repeater Control

"SELECT EmployeeID, Name, Username, Password " +
"FROM Employees", conn);
// Enclose database code in Try-Catch-Finally
try
{
// Open the connection
conn
...
ExecuteReader();
// Bind the repeater to the data source
myRepeater
...
DataBind();
// Close the data reader
reader
...
Write("Error retrieving user data
...
Close();
}
}

Figure 9
...
Using the Repeater control

359

Chapter 9: ADO
...
In this case, we’ve used the Repeater control,
which, in the server-side code, we bound to the SqlDataReader that contains
our data
...
8
...
Your code also takes care to always close the database
connection in case an error occurs along the way
...

In the following pages, you'll insert, update, and delete database records in a new
Dorknozzle Employee Directory web form
...
NET
...
Make sure
you name it EmployeeDirectory
...
master
...
aspx (excerpt)

<%@ Page Language="VB" MasterPageFile="~/Dorknozzle
...
aspx
...
The item template contains
code render blocks that will display the data from an SqlDataReader
...
9
...
9
...
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)
...
aspx
...
Data
...
Configuration
Partial Class EmployeeDirectory
Inherits System
...
UI
...
NET

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
Load
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Open()
' Execute the command
reader = comm
...
DataSource = reader
employeesRepeater
...
Close()
Finally
' Close the connection
conn
...
aspx
...
Data;
System
...
Collections;
System
...
Web
...
Web
...
Web
...
WebControls;
System
...
UI
...
WebParts;
System
...
UI
...
Data
...
Web
...
Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Define data objects
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Open();
// Execute the command
reader = comm
...
DataSource = reader;
employeesRepeater
...
Close();
}
finally
{
// Close the connection
conn
...
aspx
...
config
Dim connectionString As String =

363

Chapter 9: ADO
...
ConnectionStrings(
"Dorknozzle")
...
aspx
...
config
string connectionString = ConfigurationManager
...
ConnectionString;

Back in Chapter 5, you learned that you can store various configuration options
in Web
...
Anticipating that many applications will use Web
...
NET reserved a special place in
Web
...
If you open Web
...
Modify Web
...
config (excerpt)




connectionString="Server=localhost\SqlExpress;
Database=Dorknozzle;Integrated Security=True"
providerName="System
...
SqlClient"/>




You can add more connection strings under the connectionStrings element by
inserting add elements with three attributes: connectionString contains the
actual connection string, name gives the connection string an identifier that we
can reference within our code, and providerName indicates the type of data
provider we want to use for the connection
...
Data
...

To

retrieve configuration data from Web
...
Configuration
namespace
...
When a Catch block is not present, any exceptions that are raised
are not caught, although the code in the Finally block is still executed
...
aspx,
but we still want to ensure that the database connection is properly closed if an
error arises
...
Once
the reader has been filled with the database data, it is bound to the Repeater
control’s DataSource property, and from this point, the repeater takes control
and reads all the data from the data source
...
9
...
In our previous examples, the data source was an SqlDataReader
object, and the consumer was a Repeater control that read and displayed the
data
...
DataSource = reader
employeesRepeater
...
DataSource = reader;
employeesRepeater
...
NET includes a few controls that specialize in displaying data that comes from data sources, but you can also bind data to numerous
other controls, including lists, menus, text boxes, and so on
...
If you remember,
we left the Category and Subject drop-down lists empty back in Chapter 5
...
Sure, we could have hard-coded the values ourselves,
but imagine what would happen if additions or deletions needed to be made to
that list
...

It’s preferable to store the lists of categories and subjects in database tables, and
to bind this data to the drop-down lists in the Help Desk page
...


365

Chapter 9: ADO
...
aspx to
populate the DropDownList controls from the database
...
10
...
10
...
aspx in Design View and double-click an empty space on the
form to have the signature of the Page_Load method generated for you
...
aspx
...
Data
...
Configuration

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
Load
If Not IsPostBack Then
' Define data objects
Dim conn As SqlConnection
Dim categoryComm As SqlCommand
Dim subjectComm As SqlCommand
Dim reader As SqlDataReader
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Open()
' Execute the category command
reader = categoryComm
...
DataSource = reader
categoryList
...
DataTextField = "Category"
categoryList
...
Close()
' Execute the subjects command
reader = subjectComm
...
DataSource = reader
subjectList
...
DataTextField = "Subject"
subjectList
...
Close()
Finally
' Close the connection
conn
...
aspx
...
Data
...
NET

if (!IsPostBack)
{
// Declare objects
SqlConnection conn;
SqlCommand categoryComm;
SqlCommand subjectComm;
SqlDataReader reader;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Open();
// Execute the category command
reader = categoryComm
...
DataSource = reader;
categoryList
...
DataTextField = "Category";
categoryList
...
Close();
// Execute the subject command
reader = subjectComm
...
DataSource = reader;
subjectList
...
DataTextField = "Subject";
subjectList
...
Close();
}
finally
{
// Close the connection

368

More Data Binding

conn
...
But just what is this IsPostBack?
Earlier, in Chapter 2, we explored the View State mechanism that ASP
...
View State allows your user controls to remember their states across page loads
...
For example, when a button with a server-side
Click event handler is clicked, a post back occurs so that the server-side code
can respond to the Click event
...
In consequence, if you
click the Submit Request button ten times, Page_Load will be executed ten times
...
IsPostBack returns False if the web
form is being loaded for the first time; it returns True if the page is being loaded
because the form has been posted back to the server
...
If
we wanted to, we could refer to this property as Me
...
IsPostBack in C#
...
We’re
loading the form with data only the first time the page is loaded, because we
know that the data in the drop-down lists won’t change in response to other
changes in the form
...
For example, we might want to take such
action in a car search form in which, when the user selects a car manufacturer,

369

Chapter 9: ADO
...


Once it has been established that this is the first time the page has been loaded,
the code continues in a pattern similar to the previous code samples
...
config, create a new connection to the database,
and set up our SqlCommand objects
...
These queries are stored in two SqlCommand objects: categoryComm and
subjectComm
...
First, we execute
categoryComm to retrieve a list of categories; then, we bind that list to
categoryList:
Visual Basic

File: HelpDesk
...
vb (excerpt)

' Execute the category command
reader = categoryComm
...
DataSource = reader
categoryList
...
DataTextField = "Category"
categoryList
...
Close()
C#

File: HelpDesk
...
cs (excerpt)

// Execute the category command
reader = categoryComm
...
DataSource = reader;
categoryList
...
DataTextField = "Category";
categoryList
...
Close();

Note that not all controls handle their bindings in the same way
...
The DropDownList control is cleverly designed,
and it can also store an ID associated with each item in the list
...

The DataTextField property of the DropDownList needs to be set to the name
of the column that provides the text to be displayed, and the DataValueField
must be set to the name of the column that contains the ID
...

When the page loads, all the categories and subjects will be loaded into their respective DropDownList controls, as shown in Figure 9
...


Inserting Records
The code that inserts records from your application into a database isn’t too
different from what we’ve already seen
...
As we discussed earlier in this chapter, to execute such a query, you’d need
to use the ExecuteNonQuery method of the SqlCommand object, as INSERT queries
don’t return results
...

A typical INSERT statement is coded as follows:
Visual Basic

comm = New SqlCommand( _
"INSERT INTO HelpDesk (Field1, Field2, …) " & _
"VALUES (@Parameter1, @Parameter2, …)", conn)

Once the SqlCommand object has been created with a parameterized INSERT query,
we simply pass in the necessary parameters, similarly to the process we followed
for SELECT queries:
Visual Basic

comm
...
Add("@Parameter1", System
...
SqlDbType
...
Parameters("@Parameter1")
...
Parameters
...
Data
...
Type2)
comm
...
Value = value2

371

Chapter 9: ADO
...
Parameters
...
Data
...
Type1);
comm
...
Value = value1;
comm
...
Add("@Parameter2", System
...
SqlDbType
...
Parameters["@Parameter2"]
...

When employees visit the help desk page, they’ll fill out the necessary information,
click Submit Request, and the information will be saved within the HelpDesk
table
...

First, open HelpDesk
...

File: HelpDesk
...
We’re adding this Label control
to display errors that arise when an exception is caught while the database query
is executing
...
For example, if the database server is rebooted, and we try to
run a database query, we’ll receive an error until the database is up and running
again
...
An example of an error message
is shown in Figure 9
...

You already have a Click event handler for the Submit Request button in HelpDesk
...
The event handler should look like this:
Visual Basic

File: HelpDesk
...
vb (excerpt)

Protected Sub submitButton_Click(ByVal sender As Object, _
ByVal e As System
...
Click

372

Inserting Records

Figure 9
...
Displaying an error message in the catch block

If Page
...
aspx
...
IsValid)
{
// Code that uses the data entered by the user
}
}

373

Chapter 9: ADO
...
aspx
...
EventArgs) Handles submitButton
...
IsValid Then
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Parameters
...
Data
...
Int)
comm
...
Value = 5
comm
...
Add("@StationNumber", _
System
...
SqlDbType
...
Parameters("@StationNumber")
...
Text
comm
...
Add("@CategoryID", System
...
SqlDbType
...
Parameters("@CategoryID")
...
SelectedItem
...
Parameters
...
Data
...
Int)
comm
...
Value = _
subjectList
...
Value
comm
...
Add("@Description", _
System
...
SqlDbType
...
Parameters("@Description")
...
Text
comm
...
Add("@StatusID", System
...
SqlDbType
...
Parameters("@StatusID")
...
Open()
' Execute the command
comm
...
Redirect("HelpDesk
...
Text = _
"Error submitting the help desk request! Please " & _
"try again later, and/or change the entered data!"
Finally
' Close the connection
conn
...
aspx
...
IsValid)
{
// Define data objects
SqlConnection conn;
SqlCommand comm;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Parameters
...
Data
...
Int);
comm
...
Value = 5;
comm
...
Add("@StationNumber",
System
...
SqlDbType
...
Parameters["@StationNumber"]
...
Text;
comm
...
Add("@CategoryID", System
...
SqlDbType
...
Parameters["@CategoryID"]
...
SelectedItem
...
Parameters
...
Data
...
Int);
comm
...
Value =
subjectList
...
Value;

375

Chapter 9: ADO
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value =
descriptionTextBox
...
Parameters
...
Data
...
Int);
comm
...
Value = 1;
// Enclose database code in Try-Catch-Finally
try
{
// Open the connection
conn
...
ExecuteNonQuery();
// Reload page if the query executed successfully
Response
...
aspx");
}
catch
{
// Display error message
dbErrorMessage
...
Close();
}
}
}

Make Sure you’ve Set the Identity Property!
Note that when we’re inserting a new record into the HelpDesk table, we
rely on the ID column, RequestID, to be generated automatically for us by
the database
...

You’ll remember that, in order to make the example simpler, we hard-coded the
EmployeeID (to the value of 5), and the Status (to the value of 1)
...
12
...
For now, just make sure
that the Employees table has a record with an EmployeeID of 5, otherwise the
query won’t execute successfully
...
Redirect
...
Response
...
For example, the following line of code redirects the
user to a page called SomeForm
...
Redirect("SomeForm
...
NET

C#

Response
...
aspx");

In our example, we redirect the user back to the same web form
...
NET
would preserve all of the values that the user had typed into the form fields
...
Redirecting the user in the way outlined above
causes the browser to reload the page from scratch, clearing the form fields to
indicate the completed submission
...
Now, we can enter help desk information,
as shown in Figure 9
...

Once we click Submit Request, the Click event is raised, the submitButton_Click
method is called, all the parameters from the form are passed into the SQL
statement, and the data is inserted into the HelpDesk table
...
13
...
13
...
This gives the user a chance to review the data, make the necessary
changes, and, finally, submit the updated values
...
Parameters
...
Data
...
Type1)
comm
...
Value = value1
comm
...
Add("@Parameter2", System
...
SqlDbType
...
Parameters("@Parameter2")
...
Parameters
...
Data
...
Type1);
comm
...
Value = value1;
comm
...
Add("@Parameter2", System
...
SqlDbType
...
Parameters["@Parameter2"]
...

The important thing to remember when updating records is that you must take
care to perform the UPDATE on the correct record
...


Handle Updates with Care!
When updating a table with some new data, if you don’t specify a WHERE
clause, every record in the table will be updated with the new data, and
(usually) there’s no way to undo the action!

Let’s put all this theory into practice as we build the Admin Tools page
...
For instance,
in this section, we’ll allow an administrator to change the details of a specific
employee
...
aspx in the same way you created
the other web forms we’ve built so far
...
master master page
and a code-behind file
...

File: AdminTools
...
master"
AutoEventWireup="true" CodeFile="AdminTools
...
vb"
Inherits="AdminTools" title="Dorknozzle Admin Tools" %>

379

Chapter 9: ADO
...
14
...
14
...
NET

employeesList

In order for administrators to select the record for the employee whose details
they want to update, we’ll first have to bind the Employees table to this
DropDownList control
...
The Click event will be raised,
and the Employee ID selected from employeesList will be passed to the web
form—this will be used in an SqlCommand to retrieve the details for this employee
...

nameTextBox, usernameTextBox, addressTextBox, cityTextBox, stateTextBox,
zipTextBox, homePhoneTextBox, extensionTextBox, mobilePhoneTextBox
Within the selectButton’s Click event handler, we’ll add some code that
binds user information to these TextBox controls
...

dbErrorLabel
We use dbErrorLabel to display an error message if a database operation

fails
...
Use Visual Web Developer to generate the page’s Load event
handler, then add this code:
Visual Basic

File: AdminTools
...
vb (excerpt)

Imports System
...
SqlClient
Imports System
...
Web
...
Page
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
Load
' Read the employees list when initially loading the page
If Not IsPostBack Then

382

Updating Records

LoadEmployeesList()
End If
End Sub
Private Sub LoadEmployeesList()
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Open()
' Execute the command
reader = comm
...
DataSource = reader
employeesList
...
DataTextField = "Name"
employeesList
...
Close()
Catch
' Display error message
dbErrorLabel
...
Close()
End Try
' Disable the update button
updateButton
...
Text = ""
usernameTextBox
...
Text = ""
cityTextBox
...
NET

stateTextBox
...
Text = ""
homePhoneTextBox
...
Text = ""
mobilePhoneTextBox
...
aspx
...
Data;
System
...
Collections;
System
...
Web
...
Web
...
Web
...
WebControls;
System
...
UI
...
WebParts;
System
...
UI
...
Data
...
Web
...
Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Read the employees list when initially loading the page
if (!IsPostBack)
{
LoadEmployeesList();
}
}
private void LoadEmployeesList()
{
// Declare objects
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Open();
// Execute the command
reader = comm
...
DataSource = reader;
employeesList
...
DataTextField = "Name";
employeesList
...
Close();
}
catch
{
// Display error message
dbErrorLabel
...
Close();
}
// Disable the update button
updateButton
...
Text = "";
usernameTextBox
...
Text = "";
cityTextBox
...
Text = "";
zipTextBox
...
Text = "";
extensionTextBox
...
Text = "";
}
}

Note that we’ve put the code to populate the employeesList in a separate subroutine called LoadEmployeeList
...


385

Chapter 9: ADO
...
15
...
15
...

Again, the employees’ names are shown because the Name field is bound to the
DataTextField property of the DropDownList control
...

We need to undertake two more tasks to complete this page’s functionality
...
Then, we’ll need to handle the Click
event of the Update button, to update the information for the selected employee
...
Double-click the button in Design View to have
the Click event handler generated for you, then complete the code like this:
Visual Basic

File: AdminTools
...
vb (excerpt)

Protected Sub selectButton_Click(ByVal sender As Object, _
ByVal e As System
...
Click

386

Updating Records

Figure 9
...
Displaying employee details in the update form

' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
NET

' Add command parameters
comm
...
Add("@EmployeeID", Data
...
Int)
comm
...
Item("@EmployeeID")
...
SelectedItem
...
Open()
' Execute the command
reader = comm
...
Read() Then
nameTextBox
...
Item("Name")
...
Text = reader
...
ToString()
addressTextBox
...
Item("Address")
...
Text = reader
...
ToString()
stateTextBox
...
Item("State")
...
Text = reader
...
ToString()
homePhoneTextBox
...
Item("HomePhone")
...
Text = reader
...
ToString()
mobilePhoneTextBox
...
Item("MobilePhone")
...
Close()
' Enable the Update button
updateButton
...
Text = _
"Error loading the employee details!
"
Finally
' Close the connection
conn
...
aspx
...
config
string connectionString =

388

Updating Records

ConfigurationManager
...
ConnectionString;
// Initialize connection
conn = new SqlConnection(connectionString);
// Create command
comm = new SqlCommand(
"SELECT Name, Username, Address, City, State, Zip, " +
"HomePhone, Extension, MobilePhone FROM Employees " +
"WHERE EmployeeID = @EmployeeID", conn);
// Add command parameters
comm
...
Add("@EmployeeID", SqlDbType
...
Parameters["@EmployeeID"]
...
SelectedItem
...
Open();
// Execute the command
reader = comm
...
Read())
{
nameTextBox
...
ToString();
usernameTextBox
...
ToString();
addressTextBox
...
ToString();
cityTextBox
...
ToString();
stateTextBox
...
ToString();
zipTextBox
...
ToString();
homePhoneTextBox
...
ToString();
extensionTextBox
...
ToString();
mobilePhoneTextBox
...
ToString();
}
// Close the reader
reader
...
Enabled = true;
}
catch
{
// Display error message
dbErrorLabel
...
NET

// Close the connection
conn
...

The last thing we need to do is add code to handle the update interaction
...
The reason for this is simple: you don’t want your users
updating information before they’ve selected an employee
...
If you look at the selectButton_Click
method just before the Catch statement, you’ll notice that we enable this button
after binding the user data to the fields
...
Open AdminTools
...

Visual Web Developer will generate the signature of the event handler subroutine
(updateButton_Click) for you
...
aspx
...
EventArgs) Handles updateButton
...
config
Dim connectionString As String = _
ConfigurationManager
...
ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
' Create command
comm = New SqlCommand( _
"UPDATE Employees SET Name=@Name, Username=@Username, " & _
"Address=@Address, City=@City, State=@State, Zip=@Zip," & _
"HomePhone=@HomePhone, Extension=@Extension, " & _
"MobilePhone=@MobilePhone " & _
"WHERE EmployeeID=@EmployeeID", conn)
' Add command parameters

390

Updating Records

comm
...
Add("@Name", System
...
SqlDbType
...
Parameters("@Name")
...
Text
comm
...
Add("@Username", _
System
...
SqlDbType
...
Parameters("@Username")
...
Text
comm
...
Add("@Address", _
System
...
SqlDbType
...
Parameters("@Address")
...
Text
comm
...
Add("@City", _
System
...
SqlDbType
...
Parameters("@City")
...
Text
comm
...
Add("@State", _
System
...
SqlDbType
...
Parameters("@State")
...
Text
comm
...
Add("@Zip", System
...
SqlDbType
...
Parameters("@Zip")
...
Text
comm
...
Add("@HomePhone", _
System
...
SqlDbType
...
Parameters("@HomePhone")
...
Text
comm
...
Add("@Extension", _
System
...
SqlDbType
...
Parameters("@Extension")
...
Text
comm
...
Add("@MobilePhone", _
System
...
SqlDbType
...
Parameters("@MobilePhone")
...
Text
comm
...
Add("@EmployeeID", System
...
SqlDbType
...
Parameters("@EmployeeID")
...
SelectedItem
...
Open()
' Execute the command
comm
...
Text = _
"Error updating the employee details!
"
Finally
' Close the connection
conn
...
NET

C#

File: AdminTools
...
cs (excerpt)

protected void updateButton_Click(object sender, EventArgs e)
{
// Declare objects
SqlConnection conn;
SqlCommand comm;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Parameters
...
Data
...
NVarChar,50);
comm
...
Value = nameTextBox
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value = usernameTextBox
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value = addressTextBox
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value = cityTextBox
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value = stateTextBox
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value = zipTextBox
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value = homePhoneTextBox
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value = extensionTextBox
...
Parameters
...
Data
...
NVarChar, 50);

392

Updating Records

comm
...
Value = mobilePhoneTextBox
...
Parameters
...
Data
...
Int);
comm
...
Value =
employeesList
...
Value;
// Enclose database code in Try-Catch-Finally
try
{
// Open the connection
conn
...
ExecuteNonQuery();
}
catch
{
// Display error message
dbErrorLabel
...
Close();
}
// Refresh the employees list
LoadEmployeesList();
}

As you can see, the only real differences between this and the help desk page are
that we’re using an UPDATE query instead of an INSERT query, and we’ve had to
let the user choose an entry from the database to update
...

You’ll also notice that at the very end of this method, we call LoadEmployeesList
to reload the list of employees, as the user may have changed the name of one
of the employees
...
Once LoadEmployeesList
has executed, the page is ready for the user to select another employee for updating
...


393

Chapter 9: ADO
...
Again, most of the code for deleting records resembles that which we’ve
already seen
...
Parameters
...
Data
...
Type)
comm
...
Value = UniqueValue
C#

comm
...
Add("@UniqueFieldParameter",
System
...
SqlDbType
...
Parameters["@UniqueFieldParameter"]
...
Since we’re allowing administrators to update information within the Employees table, let’s also give them the ability to delete an
employee’s record from the database
...

Start by adding the new control at the end of AdminTools
...
aspx (excerpt)


Enabled="False" runat="server" />
Enabled="False" runat="server" />



394

Deleting Records

Next, update selectButton_Click to enable the Delete Employee button when
an employee is selected:
Visual Basic

File: AdminTools
...
vb (excerpt)

' Enable the Update button
updateButton
...
Enabled = True
Visual Basic

// Enable the Update
updateButton
...
Enabled

File: AdminTools
...
vb (excerpt)

button
= true;
button
= true;

Next, write the code for its Click event handler
...

Visual Basic

File: AdminTools
...
vb (excerpt)

Protected Sub deleteButton_Click(ByVal sender As Object, _
ByVal e As System
...
Click
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Parameters
...
Data
...
Int)
comm
...
Value = _
employeesList
...
Value
Try
' Open the connection
conn
...
ExecuteNonQuery()
Catch

395

Chapter 9: ADO
...
Text = "Error deleting employee!
"
Finally
' Close the connection
conn
...
aspx
...
config
string connectionString =
ConfigurationManager
...
ConnectionString;
// Initialize connection
conn = new SqlConnection(connectionString);
// Create command
comm = new SqlCommand("DELETE FROM Employees " +
"WHERE EmployeeID = @EmployeeID", conn);
// Add command parameters
comm
...
Add("@EmployeeID", System
...
SqlDbType
...
Parameters["@EmployeeID"]
...
SelectedItem
...
Open();
// Execute the command
comm
...
Text = "Error deleting employee!
";
}
finally
{
// Close the connection
conn
...
For testing purposes, feel free to
add more records to the Employees table using SQL Server Management Studio,
then delete them through the Dorknozzle application (if you do that, note you’ll
need to refresh the view of the Employees table manually in order to see the
changes)
...
As far as ADO
...

Let’s assume you’d prefer to use a stored procedure to add help desk requests,
rather than typing the SQL code in HelpDesk
...
vb, or HelpDesk
...
cs
...
aspx
...
aspx
...
aspx
...
config

397

Chapter 9: ADO
...
ConnectionStrings( _
"Dorknozzle")
...
CommandType = System
...
CommandType
...
Parameters
...
Data
...
Int)
comm
...
Value = 5
comm
...
Add("@StationNumber", System
...
SqlDbType
...
Parameters("@StationNumber")
...
Text
comm
...
Add("@CategoryID", System
...
SqlDbType
...
Parameters("@CategoryID")
...
SelectedItem
...
Parameters
...
Data
...
Int)
comm
...
Value = _
subjectList
...
Value
comm
...
Add("@Description", _
System
...
SqlDbType
...
Parameters("@Description")
...
Text
comm
...
Add("@StatusID", System
...
SqlDbType
...
Parameters("@StatusID")
...
aspx
...
config
string connectionString = ConfigurationManager
...
ConnectionString;
// Initialize connection
conn = new SqlConnection(connectionString);
// Create command
comm = new SqlCommand("InsertHelpDesk", conn);
// Specify we're calling a stored procedure
comm
...
Data
...
StoredProcedure;
// Add command parameters
comm
...
Add("@EmployeeID", System
...
SqlDbType
...
Parameters["@EmployeeID"]
...
Parameters
...
Data
...
Int);
comm
...
Value = stationTextBox
...
Parameters
...
Data
...
Int);
comm
...
Value =

398

Summary

categoryList
...
Value;
comm
...
Add("@SubjectID", System
...
SqlDbType
...
Parameters["@SubjectID"]
...
SelectedItem
...
Parameters
...
Data
...
NVarChar, 50);
comm
...
Value = descriptionTextBox
...
Parameters
...
Data
...
Int);
comm
...
Value = 1;

If you now load the Help Desk page, you’ll see that it works just as it used to,
but behind the scenes, it’s making use of a stored procedure
...

As you can see, using stored procedures is very easy
...
That’s it! Everything else is the same as when working with
a parameterized query
...
First, you learned about the various classes included with
ADO
...
Then,
you learned how to use these classes to create simple applications that query the
database, insert records into a database, update records within a database, and
delete records from a database
...
Later
in the chapter, you learned how to improve application performance through the
use of stored procedures
...


399

400

10

Displaying Content Using Data
Lists

Similar to the Repeater control, the DataList control allows you to bind and
customize the presentation of database data
...
In the following pages, you’ll learn:
❑ the basics of the DataList control
❑ how to handle DataList events
❑ how to edit DataList items
❑ how to handle the controls inside the DataList templates
❑ how to use Visual Web Developer to edit the DataList
Let’s get started!

DataList Basics
To learn how to use the DataList, we’ll update the Dorknozzle Employee Directory page to use a DataList control instead of a Repeater control
...

If you now open EmployeeDirectory
...
aspx (excerpt)



Employee ID:
<%#Eval("EmployeeID")%>

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

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



402

DataList Basics






You can see the output of this code in Figure 9
...
Now, let’s update
the employee directory page to use a DataList instead of a Repeater
...
aspx (excerpt)



Employee ID:
<%#Eval("EmployeeID")%>

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

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







As we’ve changed the ID for this control, we’ll need to change the name of the
control in the code-behind file as well
...
aspx
...
Open()
' Execute the command
reader = comm
...
DataSource = reader
employeesList
...
Close()
C#

File: EmployeeDirectory
...
cs (excerpt

// Open the connection
conn
...
ExecuteReader();
// Bind the reader to the DataList
employeesList
...
DataBind();

403

Chapter 10: Displaying Content Using Data Lists

// Close the reader
reader
...
That’s largely because the Repeater was displaying a basic
list of data anyway
...
Both Repeater and DataList support the ItemTemplate and SeparatorTemplate templates, but in case of the DataList, the templates specify the content that is to be inserted in the td elements of the table
...
1 illustrates
...
1
...
Depending on

404

DataList Basics

the extra features you need, you can use either the DataList control (covered
in this chapter), or the GridView or DetailsView controls (which you’ll
learn about in Chapter 12)
...
The DataList
offers a number of templates:
ItemTemplate

This template is replicated for each record that’s read from the data source
...

AlternatingItemTemplate

If this template is defined, it will be used instead of ItemTemplate to display
every second element
...
The DataList
control doesn’t automatically give the user a way to select an item in the list,
but you can mark an item as selected by setting the DataLists control’s
SelectedIndex property
...
Setting SelectedIndex to -1 unselects any selected item
...
We can set the item being edited using the EditItemIndex
property of the DataList, which operates in the same way as the
SelectedIndex property
...

HeaderTemplate

This template specifies the content to be used for the list header
...

SeparatorTemplate

This template specifies the content to be inserted between two consecutive
data items
...


405

Chapter 10: Displaying Content Using Data Lists

Handling DataList Events
One problem you may encounter when working with container controls such as
the DataList or the Repeater is that you can’t access the controls inside their
templates directly from your code
...
The following code would generate an error:
Visual Basic

' Don't try this at home
myButton
...

So, if we can’t handle events raised by the buttons and links inside a template,
how can we interact with the data in each template? We’ll improve our employee
directory by making a simpler, basic view of the items, and add a “View More”
link that users can click in order to access more details about the employee
...

After we implement this feature, our list will appear as shown in Figure 10
...

You’ll be able to view more details about any employee by clicking on the appropriate link
...
aspx, and modify the ItemTemplate of the DataList
as shown below:
Visual Basic

File: EmployeeDirectory
...
2
...
aspx (excerpt)



EnableViewState="false" />
Name: <%#Eval("Name")%>

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


407

Chapter 10: Displaying Content Using Data Lists

Text=<%#"View more details about " + Eval("Name")%>
CommandName="MoreDetailsPlease"
CommandArgument=<%#Eval("EmployeeID")%> />







Here, we’ve added two controls
...
Even though the LinkButton looks
like a link, it really behaves like a button
...
If you prefer, you can
change the LinkButton to a Button, and the functionality will remain identical
...
2
...
In order
to react to this LinkButton being clicked, you might think that you’d need to
handle its Click event
...
Also, when the
code executes, you’ll have more instances of this button—so on the server side,
you’ll need a way to know which of them was clicked!
Luckily, ASP
...

Whenever a button inside a DataList generates a Click event, the DataList
generates itself a ItemCommand event
...

Within the ItemCommand event handler, we can retrieve the data contained in
the LinkButton’s CommandName and CommandArgument properties
...

Take another look at the button definition from the DataList’s ItemTemplate:
Visual Basic

File: EmployeeDirectory
...
We’re able to read this data from the
DataList’s ItemCommand event handler
...

Open EmployeeDirectory
...
There, click the yellow lightning symbol to
open the list of events, and double-click the ItemCommand event in that list
...

If you were to open the DataList’s properties again, you’d see the event handler
name appearing next to the event name, as depicted in Figure 10
...


Figure 10
...
The ItemCommand event in the Properties window

Modify the code in employeesList_ItemCommand as shown below
...
aspx
...
Web
...
WebControls
...
ItemCommand
' Which button was clicked?
If e
...
Item
...
Text = "Employee ID: " & e
...
aspx
...
CommandName == "MoreDetailsPlease")
{
// Find the Literal control in the DataList item
Literal li;
li = (Literal)e
...
FindControl("extraDetailsLiteral");
// Add content to the Literal control
li
...
CommandArgument +
"

";
}
}

Our code is almost ready to execute, but we should make one more minor tweak
before we execute this page
...
Let’s change this code so that the data binding only takes
place when the page is being loaded for the first time
...
Modify
the code as shown below, moving the current contents of Page_Load into a new
method called BindList:
Visual Basic

File: EmployeeDirectory
...
vb (excerpt)

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
Load
If Not IsPostBack Then
BindList()
End If
End Sub
Protected Sub BindList()
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader

End Sub
C#

File: EmployeeDirectory
...
cs (excerpt)

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

410

Handling DataList Events

BindList();
}
}
protected void BindList()
{
// Define data objects
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;

}

Execute the project and click the View more details links to see the employee ID
appear, as shown in Figure 10
...


Figure 10
...
The Employee Directory showing employee IDs

The code in employeesList_ItemCommand shows how you can work with controls
inside a DataList template, and how to handle their events
...
CommandName in the event handler,
which will be populated with the value of the CommandName property of the control
that was clicked
...
aspx
...
CommandName = "MoreDetailsPlease" Then
C#

File: EmployeeDirectory
...
cs (excerpt)

// Which button was clicked?
if (e
...
But,
given that this control is inside our template, how can we access it through code?
To use a control inside a DataList, we use the FindControl method of the object
e
...
Here, e
...
So, in order to obtain a reference to the control with
the ID extraDetailsLiteral, we use FindControl like this:
Visual Basic

File: EmployeeDirectory
...
vb (excerpt)

' Find the Literal control in the DataList item
Dim li As Literal
li = e
...
FindControl("extraDetailsLiteral")

Note that FindControl returns a generic Control object
...
In C#, we need an explicit cast, as shown here:
C#

File: EmployeeDirectory
...
cs (excerpt)

// Find the Literal control in the DataList item
Literal li;
li = (Literal)e
...
FindControl("extraDetailsLiteral");

Finally, once we have access to the Literal control in a local variable, setting its
contents is a piece of cake:
Visual Basic

File: EmployeeDirectory
...
vb (excerpt)

' Add content to the Literal control
li
...
CommandArgument & _
"
"

412

Editing DataList Items and Using Templates

C#

File: EmployeeDirectory
...
cs (excerpt)

// Add content to the Literal control
li
...
CommandArgument +
"
";

Disabling View State
If you take a look at the definition of the extraDetailsLiteral control
in EmployeeDirectory
...
aspx (excerpt)

EnableViewState="false" />
When this property is False, its contents aren’t persisted during postback
events
...
This way, at any
given moment, no more than one employee’s ID will be displayed
...


Editing DataList Items and Using
Templates
Continuing our journey into the world of DataList, let’s learn a little more about
its templates, and see how you can use the EditItemTemplate to edit its contents
...

Start by adding another button to the ItemTemplate of the DataList
...

File: EmployeeDirectory
...

When one of the DataList items is in edit mode, the EditItemTemplate template
of the DataList is used to generate the contents of that item
...

Modify EmployeeDirectory
...
The EditItemTemplate contains TextBox controls into which the user
can enter the employee’s name and username, and two buttons: Update Item and
Cancel Editing, whose names are self-explanatory
...
aspx (excerpt)


Name: Text=<%#Eval("Name")%> />

Username: Text=<%#Eval("Username")%> />

Text="Update Item" CommandName="UpdateItem"
CommandArgument=<%#Eval("EmployeeID")%> />
or
Text="Cancel Editing" CommandName="CancelEditing"
CommandArgument=<%#Eval("EmployeeID")%> />


Finally, before you can see your new template, we need to handle the Edit employee button
...
This time, the CommandName of the new button is EditItem, and when
we discover that this button was clicked, we’ll put the item into edit mode
...

Add this code:
Visual Basic

File: EmployeeDirectory
...
vb (excerpt)

Protected Sub employeesList_ItemCommand(ByVal source As Object, _
ByVal e As System
...
UI
...
DataListCommandEventArgs) _

414

Editing DataList Items and Using Templates

Handles employeesList
...
CommandName = "MoreDetailsPlease" Then
' Find the Literal control in the DataList item
Dim li As Literal
li = e
...
FindControl("extraDetailsLiteral")
' Add content to the Literal control
li
...
CommandArgument & _
"
"
ElseIf e
...
EditItemIndex = e
...
ItemIndex
' Bind again the list to update the list
BindList()
End If
End Sub
C#

File: EmployeeDirectory
...
cs (excerpt)

protected void employeesList_ItemCommand(object source,
DataListCommandEventArgs e)
{
// Which button was clicked?
if (e
...
Item
...
Text = "Employee ID: " + e
...
CommandName == "EditItem")
{
// Set the index of the item being edited
employeesList
...
Item
...
5
...
5
...
We’ll take them one at a time, starting with Cancel Editing, which
is easier to handle
...
aspx
...
Web
...
WebControls
...
ItemCommand
' Which button was clicked?
If e
...
Item
...
Text = "Employee ID: " & e
...
CommandName = "EditItem" Then
' Set the index of the item being edited
employeesList
...
Item
...
CommandName = "CancelEditing" Then
' Cancel edit mode
employeesList
...
aspx
...
CommandName == "MoreDetailsPlease")
{
// Find the Literal control in the DataList item
Literal li;
li = (Literal)e
...
FindControl("extraDetailsLiteral");
// Add content to the Literal control
li
...
CommandArgument +
"

";
}
else if (e
...
EditItemIndex = e
...
ItemIndex;
// Bind again the list to update the list
BindList();
}
else if (e
...
EditItemIndex = -1;
// Refresh the DataList
BindList();
}
}

Execute your project again and check that your new button works
...
You simply need to set the EditItemIndex
property of the DataList to -1, then refresh the DataList’s contents
...
We read the ID of the employee whose details are being edited from the button’s CommandArgument prop-

417

Chapter 10: Displaying Content Using Data Lists

erty, and the employee’s new name and username from the TextBox control
...

Visual Basic

File: EmployeeDirectory
...
vb (excerpt)

ElseIf e
...
EditItemIndex = -1
' Refresh the DataList
BindList()
ElseIf e
...
CommandArgument
' Get the new username
Dim nameTextBox As TextBox = _
e
...
FindControl("nameTextBox")
Dim newName As String = nameTextBox
...
Item
...
Text
' Update the item
UpdateItem(employeeId, newName, newUsername)
' Cancel edit mode
employeesList
...
aspx
...
CommandName == "CancelEditing")
{
// Cancel edit mode
employeesList
...
CommandName == "UpdateItem")
{
// Get the employee ID
int employeeId = Convert
...
CommandArgument);
// Get the new username
TextBox nameTextBox =
(TextBox)e
...
FindControl("nameTextBox");
string newName = nameTextBox
...
Item
...
Text;
// Update the item
UpdateItem(employeeId, newName, newUsername);
// Cancel edit mode
employeesList
...
We’ve created a separate method to make the code easier to
manage
...
aspx
...
config
Dim connectionString As String = _
ConfigurationManager
...
ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
' Create command
comm = New SqlCommand("UpdateEmployee", conn)
' Specify we're calling a stored procedure
comm
...
Data
...
StoredProcedure
' Add command parameters
comm
...
Add("@EmployeeID", Data
...
Int)
comm
...
Value = employeeId
comm
...
Add("@NewName", Data
...
NVarChar, 50)
comm
...
Value = newName
comm
...
Add("@NewUsername", Data
...
NVarChar, 50)
comm
...
Value = newUsername
' Enclose database code in Try-Catch-Finally
Try
' Open the connection
conn
...
ExecuteNonQuery()

419

Chapter 10: Displaying Content Using Data Lists

Finally
' Close the connection
conn
...
aspx
...
config
string connectionString =
ConfigurationManager
...
ConnectionString;
// Initialize connection
conn = new SqlConnection(connectionString);
// Create command
comm = new SqlCommand("UpdateEmployee", conn);
// Specify we're calling a stored procedure
comm
...
Data
...
StoredProcedure;
// Add command parameters
comm
...
Add("@EmployeeID", SqlDbType
...
Parameters["@EmployeeID"]
...
Parameters
...
NVarChar, 50);
comm
...
Value = newName;
comm
...
Add("@NewUsername", SqlDbType
...
Parameters["@NewUsername"]
...
Open();
// Execute the command
comm
...
Close();
}
}

420

Editing DataList Items and Using Templates

Once the parameters are all prepared, the UpdateItem method calls the UpdateEmployee stored procedure, which performs the database operation
...
You should see a display like the one shown
in Figure 10
...


Figure 10
...
Viewing an employee in edit mode

421

Chapter 10: Displaying Content Using Data Lists

Figure 10
...
Editing the username

Change the name or username, and click Update Item to see the listed data change
...
7, you can see that I’ve changed Zak’s username to zakNew
...

One of these slick features is the smart tag, which appears as a little arrow button
in the upper-right part of the control when the cursor is hovered over the control
in Design View
...
If you open
EmployeeDirectory
...
8
...


422

DataList and Visual Web Developer

Figure 10
...
The smart tag options of DataList

If you click Edit Templates, you can build the DataList’s templates visually, as
Figure 10
...


Figure 10
...
Building the DataList’s templates visually

We’ll generally write most of the code by hand, but it’s good to know that you
also have this visual option
...
We can access the same settings
through the Properties window, but with the DataList we have another way to
set these properties
...
You’ll learn a lot more about this in Chapter 12
...
I
left this discussion until the end of the chapter to give you the chance to play
with it a little beforehand
...
10 illustrates
...
10
...
11
...
If you look at the DataList
definition in EmployeeDirectory
...
11
...
Until then, enjoy
the benefits of having a modern-looking, functional employee directory!

Summary
As you’ve seen, DataLists provide flexibility and power in terms of presenting
database data dynamically within the browser
...
You also learned how to edit data in your DataList control,
and how to access controls located in the DataList templates
...


426

11

Managing Content Using Grid
View and Details View

In the previous chapters, you learned some of the important concepts surrounding
data access and presentation
...
You also learned
that in order to retrieve data from the database table, we must write an SQL
statement within a command using the SqlCommand class
...
Finally, you learned that presenting the data within the
SqlDataReader was simply a matter of binding the SqlDataReader to a data
control such as the Repeater or DataList controls
...

So far, these two controls have been great! They certainly have their place, and
I’m not about to discourage you from using them
...
Within those table row
tags, we also had to add code render blocks to display the contents of the data
source
...
HTML table
row tags still have to be added within the , ,
and tags, and code render blocks must still be used within

Chapter 11: Managing Content Using Grid View and Details View

the table data cells
...

Here, we’ll learn about two more controls that offer much more functionality
and make it very easy for you to create a table: GridView and DetailsView
...
NET’s set of data controls, give developers
much more power and flexibility over presentation, as you’ll see in the next few
sections
...


GridView vs DataGrid
The GridView control supersedes the DataGrid control, which was the
star of all data-displaying controls in ASP
...
0 and 1
...
The DataGrid
is still present in ASP
...
0 for backwards-compatibility purposes, but
for any new development, the GridView is recommended
...
NET 2
...


Using the GridView Control
The GridView control solves a problem that has plagued developers for years:
data presentation
...
Similar to the Repeater control, the GridView can
also automatically display all the content contained in an SqlDataReader on a
page, based on styles we set within its templates
...
e
...

To sum up, GridView controls provide the following functionality:
❑ database table-like presentation
❑ table headers and footers
❑ paging
❑ sorting

428

Using the GridView Control

❑ style modification through templates
❑ customizable columns for advanced editing
You’ll learn about some of these features in this chapter, though we’ll leave the
more advanced ones (sorting, paging, and editing) for the next chapter
...
NET server control, GridView controls are added to the
page using a specific element:


Once we add the GridView to the page, we can bind an SqlDataReader to it as
follows:
Visual Basic

myGridView
...
DataBind()
C#

myGridView
...
DataBind();

So far, the GridView doesn’t seem to function very differently from the Repeater
control, right? Think again! The Repeater control didn’t work unless we specified
content within the required and tags
...

Let’s take a look at GridView in action as we develop the Dorknozzle intranet’s
address book page
...
aspx, based on the
Dorknozzle
...
Also, make sure the new web form uses a codebehind file
...
aspx, and complete its code as shown in the following
code snippet
...
aspx (excerpt)

<%@ Page Language="VB" MasterPageFile="~/DorkNozzle
...
aspx
...
1 indicates
...
1
...
aspx in Design View

Now, double-click on an empty portion of the page to have the form’s Page_Load
event handler generated for you in the code-behind file
...
Data
...
aspx
...
Web
...
Page
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System
...
Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Open()
' Execute the command
reader = comm
...
DataSource = reader
grid
...
Close()
Finally
' Close the connection
conn
...
aspx
...
Data;
System
...
Collections;
System
...
Web
...
Web
...
Web
...
WebControls;
System
...
UI
...
WebParts;
System
...
UI
...
Data
...
Web
...
Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
// Define data objects
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Open();
// Execute the command
reader = comm
...
DataSource = reader;
grid
...
Close();
}
finally
{
// Close the connection
conn
...

Now save your work and open the page in the browser
...
2 shows how
the GridView presents all of the data within the Employees table in a cleanly
formatted structure
...
2
...
You’ll notice that the GridView closely resembles the
structure of the query’s result as you might see it in SQL Server Management
Studio
...

If you look at the generated page source (right-click the page in browser and
choose View Source or similar), you’ll see that the GridView indeed generated a
table for you:
id="ctl00_ContentPlaceHolder1_grid"
style="border-collapse:collapse;">






















EmployeeIDNameCityStateMobilePhone
1Zak RuvalcabaSan DiegoCa555-555-5551
2Jessica RuvalcabaSan DiegoCa555-555-5552


Formatted for Readability
The HTML generated by ASP
...

You’ll find that ASP
...
We’ve simply
made it a little easier to read; the two HTML tables are otherwise identical
...

The GridView automatically displays all columns retrieved from the database in
the order in which they’re sent from the database
...

Let’s learn how to customize the GridView by selecting which columns to show,
in what order
...
We need to retrieve
the table’s primary key because it’s required for any database operations that
involve the unique identification of a record (including tasks such as editing or
deleting an employee from the list)
...


Customizing the GridView Columns
Our next task is to customize the columns displayed by the GridView
...


Filtering Table Columns
The columns you can display in the GridView must be a subset of the
columns you’re retrieving from the database
...


If you wish to restrict the information that appears within your GridView, you
can select the columns you want to display by making a few simple modifications
...

One of the properties available to GridView is AutoGenerateColumns, which is
set to True by default
...

If you set this property to False and test it in the browser, you’ll find that the
grid doesn’t show up any more
...
To do so, list the columns inside the
and
tags, as shown below:
File: AddressBook
...
Each BoundField control
has a DataField property, which specifies the name of the column, and a
HeaderText property, which sets the name of the column as you want it displayed
to the user
...
This time, only the columns
that you specified to be bound are displayed in the GridView
...
3
...

We’ve now succeeded in displaying only the information we want to display, but
the GridView still looks plain
...


Styling the GridView with Templates, Skins, and
CSS
The GridView control offers a number of design-time features that are tightly
integrated with the Visual Web Developer designer
...
4 illustrates
...
3
...
4
...
Additionally, we want to add a new skin
definition for the GridView (you learned about skins back in Chapter 5), so that
all the GridView controls throughout our site have a standard appearance
...
css file from the App_Themes/Blue folder and add these
styles to it:
File: Dorknozzle
...
GridMain
{
border-right: gainsboro thin solid;
border-top: gainsboro thin solid;
border-left: gainsboro thin solid;
border-bottom: gainsboro thin solid;
background-color: #333333;
width: 400px;
}

...
GridSelectedRow
{

438

Styling the GridView with Templates, Skins, and CSS

background-color: #E6E6FA;
}

...
skin in App_Themes/Blue by adding this
skin definition:
File: SkinFile
...
aspx doesn’t
contain any styling details, as shown here:
File: AddressBook
...
5
...
Save your work and view the results in the browser
...
5?
Congratulations! You’ve harnessed the power of CSS and skin files, and combined
it with the flexibility of GridView to easily create a good-looking address book!
As you can see, you can style the items in the GridView by altering their font
types, colors, and sizes
...
Now, when the GridView is
viewed in the browser, we see a little more room between cells, and the lines
surrounding the GridView are gone
...
The
next step will be to allow users to select one of the rows in the GridView so they
can view more information about the selected employee
...
For instance, we could create a
ButtonField column, which displays a button in each row
...
When the
grid enters edit mode, this field renders itself as an editable text box, as we’ll
see later
...
When clicked, the button triggers a configurable event that you

can handle within your code to respond to the user’s action
...

CheckBoxField
The CheckBoxField displays a checkbox in each row, allowing you to easily

present Boolean data in the display
...
The actions performed by these buttons depend on the grid’s current
state
...

HyperLinkField
Use the HyperLinkField to display a clickable link within the GridView
...

ImageField

This control displays an image inside your grid
...


441

Chapter 11: Managing Content Using Grid View and Details View

Figure 11
...
Adding a new GridView column

If you’re using Visual Web Developer, you can quickly and easily add a new
column to your table in Design View
...
item, as shown in Figure 11
...

In the dialog that appears, change the field type to ButtonField, the command
name to Select, and set the Text field to Select, so the dialog appears as it does
in Figure 11
...


Figure 11
...
Adding a new field

After clicking OK, your brand new column shows up in Design View
...
aspx (excerpt)

AutoGenerateColumns="false">




442

Selecting Grid Records

HeaderText="Mobile Phone" />




If you execute the project now, and click the new button, the row will become
highlighted, as Figure 11
...
Notice that you didn’t write any code to
implement this feature? We’re relying on the functionality provided by the
ButtonField control when it’s CommandName property is set to Select, and the
style settings you set earlier, to produce this functionality
...
8
...
When the Select button is pressed,
the GridView fires the SelectedIndexChanged event, which we handle if we need
to do any further processing
...


443

Chapter 11: Managing Content Using Grid View and Details View

Generating Default Event Handlers
Double-clicking a control in the designer causes Visual Web Developer to
generate the handler of the control’s default event
...
Remember that you can use the Properties window
to have Visual Web Developer generate handlers for other events—just click
the lightning icon in the Properties window, then double-click on any of the
listed events
...
aspx a label that we can use to display some
details of the selected record
...
aspx (excerpt)







Now, generate the SelectedIndexChanged event handler by double-clicking the
GridView control in Design View, then update the event handler to display a
short message about the selected record:
Visual Basic

File: AddressBook
...
vb (excerpt)

Protected Sub grid_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System
...
SelectedIndexChanged
' Obtain the index of the selected row
Dim selectedRowIndex As Integer
selectedRowIndex = grid
...
Rows(selectedRowIndex)
Dim name As String = row
...
Text
' Update the details label
detailsLabel
...
"
End Sub
C#

File: AddressBook
...
cs (excerpt)

protected void grid_SelectedIndexChanged(object sender,
EventArgs e)
{
// Obtain the index of the selected row
int selectedRowIndex;
selectedRowIndex = grid
...
Rows[selectedRowIndex];
string name = row
...
Text;
// Update the details label
detailsLabel
...
";
}

Execute the project, and select one of the records
...
9
...
9
...
NET 2
...
You’ll find
this control very useful when you need to display details about a record that

445

Chapter 11: Managing Content Using Grid View and Details View

contains many fields—so many, in fact, that the main grid can’t display all of
them
...
For instance, an ecommerce site might initially present users with only a little information about all available products, to reduce download time and make the information more readable
...

Let’s see how this works by using a GridView and a DetailsView in our Address
Book web form
...
aspx (excerpt)







Next, we’ll modify the BindGrid method to specify the grid’s data key
...
We’ll use it to store the
EmployeeID of each record
...

Add this row to your code-behind file:
Visual Basic

File: AddressBook
...
vb (excerpt)

' Open the connection
conn
...
ExecuteReader()
' Fill the grid with data
grid
...
DataKeyNames = New String() {"EmployeeID"}
grid
...
Close()

446

Using the DetailsView Control

Figure 11
...
The DetailsView control in action

C#

File: AddressBook
...
cs (excerpt)

// Open the connection
conn
...
ExecuteReader();
// Fill the grid with data
grid
...
DataKeyNames = new string[] { "EmployeeID" };
grid
...
Close();

As you can see, we tell the GridView which keys to store by setting the
DataKeyNames property
...
In this case, we create an array that contains just one value: EmployeeID
...

After you make this change, you’ll be able to access the EmployeeID value for
any given row through the GridView’s DataKeys property
...
In the GridView’s SelectedIndexChanged event handler, we just need to make another database query to read the
details we want to display for the selected employee, then simply feed the results
to the DetailsView object, like this:
Visual Basic

File: AddressBook
...
vb (excerpt)

Protected Sub grid_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System
...
SelectedIndexChanged
BindDetails()
End Sub
Private Sub BindDetails()
' Obtain the index of the selected row
Dim selectedRowIndex As Integer = grid
...
DataKeys(selectedRowIndex)
...
config
Dim connectionString As String = _
ConfigurationManager
...
ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
' Create command
comm = New SqlCommand( _
"SELECT EmployeeID, Name, Address, City, State, Zip, " & _
"HomePhone, Extension FROM Employees " & _
"WHERE EmployeeID=@EmployeeID", conn)
' Add the EmployeeID parameter
comm
...
Add("EmployeeID", Data
...
Int)
comm
...
Value = employeeId
' Enclose database code in Try-Catch-Finally

448

Using the DetailsView Control

Try
' Open the connection
conn
...
ExecuteReader()
' Fill the grid with data
employeeDetails
...
DataKeyNames = New String() {"EmployeeID"}
employeeDetails
...
Close()
Finally
' Close the connection
conn
...
aspx
...
SelectedIndex;
// Read the employee ID
int employeeId = (int) grid
...
Value;
// Define data objects
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Parameters
...
Int);

449

Chapter 11: Managing Content Using Grid View and Details View

comm
...
Value = employeeId;
// Enclose database code in Try-Catch-Finally
try
{
// Open the connection
conn
...
ExecuteReader();
// Fill the grid with data
employeeDetails
...
DataKeyNames = new string[] {"EmployeeID"};
employeeDetails
...
Close();
}
finally
{
// Close the connection
conn
...
10
...
We’ll start by changing the row headings in
the left-hand column
...
aspx and modify the DetailsView
control like this:
File: AddressBook
...
11
...
We set
the AutoGenerateRows property to False; then, we define the fields we want to
show, and create a HeaderTemplate which displays the name of the employee in
the header—we’ll see what this looks like in a minute
...
skin:

451

Chapter 11: Managing Content Using Grid View and Details View

File: SkinFile
...
Save your work, open AddressBook
...
You should see something similar to
Figure 11
...

We’re really making progress now
...


GridView and DetailsView Events
In order to use the GridView and DetailsView controls effectively, we need to
know how to handle their events
...

Earlier, you learned how to respond to the user’s clicking of the Select button by
handling the GridView’s SelectedIndexChanged event
...
The editing features of the GridView and the DetailsView
are very similar, so you can apply the same principles, and even almost the same
code, to both of them
...
Once one of
the Edit buttons has been clicked, the row (in case of GridView) or the entire
form (in case of DetailsView) will become editable, and instead of an Edit button,
users will see Update and Cancel buttons
...
If you don’t like their default edit mode appearances, you
can customize them using templates
...
Figure 11
...


Figure 11
...
GridView in edit mode

Figure 11
...


Figure 11
...
DetailsView in edit mode

453

Chapter 11: Managing Content Using Grid View and Details View

When command buttons such as Edit are clicked, they raise events that we can
handle on the server side
...
The action types
and the events they trigger are listed in Table 11
...


Table 11
...
GridView action types and the events they trigger
Action

Events triggered when clicked

Select

SelectedIndexChanging, SelectIndexChanged

Edit

RowEditing

Update

RowUpdating, RowUpdated

Cancel

RowCancelingEdit

Delete

RowDeleting, RowDeleted

(sorting buttons)

RowSorting, RowSorted

(custom action)

RowCommand

The DetailsView control, on the other hand, has buttons and events that refer
to items, rather than rows, which makes sense when you realize that DetailsView
is used to display the items in one record, while GridView displays a few items
from many records
...
2
...
2
...
e
...
e
...
The events that end in “ing” are fired

just before their past tense counterparts, and should be handled only if you want
to implement some logic to determine whether the action in question should be
performed
...

We saw such an event handler when we handled the SelectIndexChanged event
of our GridView control
...

If we wanted to disallow the selection of a particular employee (say, the employee
with the ID 1), we could do so by setting e
...
SelectedIndexChanging
' Obtain the index of the selected row
Dim selectedRowIndex As Integer = grid
...
DataKeys(selectedRowIndex)
...
Cancel = False
End If
End Sub
C#

protected void grid_SelectedIndexChanging(object sender,
GridViewSelectEventArgs e)
{
// Obtain the index of the selected row
int selectedRowIndex = grid
...
DataKeys[selectedRowIndex]
...
Cancel = false;
}
}

455

Chapter 11: Managing Content Using Grid View and Details View

Where’s RowEdited?
Note that, in the case of the Edit action in the GridView, there’s no
RowEdited event
...
More specifically, when a row enters edit mode, it is displayed
using the default editing style of the column
...


Entering Edit Mode
To get a better grasp on all this theory, let’s look at another example
...
To implement
GridView or DetailsView editing, we can use a CommandField column
...
Open AddressBook
...
In the Choose a field type drop-down,
select CommandField, and check the Edit/Update checkbox, as shown in Figure 11
...


Figure 11
...
Adding the Edit/Update CommandField

If you’d prefer to add the new column by hand, do so by adding it in AddressBook
...
Either way, you should end up with the following code:

456

Entering Edit Mode

File: AddressBook
...
If you execute the project and click that Edit link, an exception
will be thrown, telling you that you didn’t handle the ModeChanging event
...

To have Visual Web Developer generate the ModeChanging event signature for
you, open AddressBook
...
This will generate an empty event handler for you, and take you straight
to the function in the code-behind file
...
aspx
...
Web
...
WebControls
...
ModeChanging
' Change current mode to the selected one
employeeDetails
...
NewMode)
' Rebind the grid
BindDetails()
End Sub

457

Chapter 11: Managing Content Using Grid View and Details View

C#

File: AddressBook
...
cs (excerpt)

protected void employeeDetails_ModeChanging(object sender,
DetailsViewModeEventArgs e)
{
// Change current mode to the selected one
employeeDetails
...
NewMode);
// Rebind the grid
BindDetails();
}

Execute the project and click the Edit button
...
15
...
15
...
The DetailsView

458

Using Templates

control supports three display modes
...
ReadOnly

This is the default mode, which is used to display data
...

DetailsViewMode
...
We saw this mode in action
earlier, when we clicked the Edit button
...
Insert

We use this mode to insert a new record
...

If you look at the employeeDetails_ModeChanging, you’ll see it receives a parameter named e that is an object of class DetailsViewModeEventArgs
...
Its value will be
DetailsViewMode
...
We pass this value to the DetailsView control’s
ChangeMode method, which does exactly as its name suggests: it changes the mode
of the DetailsView
...

However, note that once you switch to edit mode, clicking the Update button
will generate an error, because we still haven’t handled the ItemUpdating event
that’s fired when the user tries to save changes to a record
...


Using Templates
The built-in column types are sufficiently varied and configurable to provide for
most of the functionality you’re likely to need, but in cases where further customization is required, you can make the desired changes using templates
...
Selecting that option opens a dialog that provides us with a great deal of control
over the options for each column or field
...
Let’s see
how this works
...
In the dialog that appears, select the Address field from the Selected fields
list, as shown in Figure 11
...


Figure 11
...
Editing a field’s properties

Click the Convert this field into a TemplateField link to have Visual Web Developer
create a template that simulates the current functionality of the field, then click
OK to close the dialog
...
aspx to Source View
...
aspx (excerpt)

AutoGenerateRows="False">



Text='<%# Bind("Address") %>'>



460

Using Templates

Text='<%# Bind("Address") %>'>



Text='<%# Bind("Address") %>'>







<%#Eval("Name")%>



Pretty cool, huh? Visual Web Developer did a little bit of magic for us: it replaced
the BoundField column that used to display the address with a TemplateField
containing an ItemTemplate, an EditItemTemplate, and an InsertItemTemplate
...
The difference is that now you can easily refer to these inner controls
from your code, you can easily change their appearance using custom HTML
code, and, if you wish, you can replace them with totally different controls
...
For example, you can widen the TextBox controls used
to edit your fields, as well as performing other kinds of customizations
...


Beware of ReadOnly
Note that if you set a column as read-only (by setting the column’s ReadOnly
property to True) prior to its conversion, Visual Web Developer will use a
Label control instead of a TextBox control in the EditItemTemplate for
that field
...


Now, convert the other fields—except for CommandField—to template fields
...
To keep things simple, we’re only

461

Chapter 11: Managing Content Using Grid View and Details View

going to make changes to the Address and City fields in the code samples provided
here—you can update the others yourself
...
aspx (excerpt)



Text='<%# Bind("Address") %>'>


Text='<%# Bind("Address") %>'>


Text='<%# Bind("Address") %>'>




Text='<%# Bind("City") %>'>


Text='<%# Bind("City") %>'>


Text='<%# Bind("City") %>'>



Updating Employee Details
To keep the code in this chapter short, we’re only showing the code required
to update a couple of the fields in the Employees table
...


Execute your project, load the address book, select one employee, and click the
Edit link to ensure everything works (and looks) as shown in Figure 11
...

1

If you’re feeling lazy, you’ll be pleased to hear that updating the other fields is optional for the
purposes of this chapter
...
17
...
To begin, we’ll generate the
ItemUpdating event handler
...

Open AddressBook
...
There, double-click the ItemUpdating row to
have the designer generate the employeeDetails_ItemUpdating method for you,
and update the handler with the code shown below:
Visual Basic

File: AddressBook
...
vb (excerpt)

Protected Sub employeeDetails_ItemUpdating( _
ByVal sender As Object, ByVal e As _
System
...
UI
...
DetailsViewUpdateEventArgs) _
Handles employeeDetails
...
DataKey
...
FindControl("editAddressTextBox")
Dim newCityTextBox As TextBox = _
employeeDetails
...
Text
Dim newCity As String = newCityTextBox
...
config
Dim connectionString As String = _
ConfigurationManager
...
ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
' Create command
comm = New SqlCommand("UpdateEmployeeDetails", conn)
comm
...
CommandType
...
Parameters
...
SqlDbType
...
Parameters("@EmployeeID")
...
Parameters
...
SqlDbType
...
Parameters("@NewAddress")
...
Parameters
...
SqlDbType
...
Parameters("@NewCity")
...
Open()
' Execute the command
comm
...
Close()
End Try
' Exit edit mode
employeeDetails
...
ReadOnly)
' Reload the employees grid
BindGrid()
' Reload the details view
BindDetails()
End Sub
C#

File: AddressBook
...
cs (excerpt)

protected void employeeDetails_ItemUpdating(object sender,
DetailsViewUpdateEventArgs e)

464

Updating DetailsView Records

{
// Read the employee from the DetailsView object
int employeeId = (int)employeeDetails
...
Value;
// Find the TextBox controls with updated data
TextBox newAddressTextBox =
(TextBox)employeeDetails
...
FindControl("editCityTextBox");
// Extract the updated data from the TextBoxes
string newAddress = newAddressTextBox
...
Text;
// Define data objects
SqlConnection conn;
SqlCommand comm;
// Initialize connection
string connectionString =
ConfigurationManager
...
ConnectionString;
// Initialize connection
conn = new SqlConnection(connectionString);
// Create command
comm = new SqlCommand("UpdateEmployeeDetails", conn);
comm
...
StoredProcedure;
// Add command parameters
comm
...
Add("EmployeeID", SqlDbType
...
Parameters["EmployeeID"]
...
Parameters
...
NVarChar, 50);
comm
...
Value = newAddress;
comm
...
Add("NewCity", SqlDbType
...
Parameters["NewCity"]
...
Open();
// Execute the command
comm
...
Close();
}
// Exit edit mode
employeeDetails
...
ReadOnly);
// Reload the employees grid

465

Chapter 11: Managing Content Using Grid View and Details View

BindGrid();
// Reload the details view
BindDetails();
}

This code is pretty straightforward
...
As we saw earlier, the DetailsView, like the GridView,
is able to store the ID of the record (or records) it’s displaying
...
We
read this information in the ItemUpdating event handler, like so:
Visual Basic

File: AddressBook
...
vb (excerpt)

' Read the employee from the DetailsView object
Dim employeeId As Integer = employeeDetails
...
Value
C#

File: AddressBook
...
cs (excerpt)

// Read the employee from the DetailsView object
int employeeId = (int) employeeDetails
...
Value;

The next step is to find the TextBox objects that contain the updated data
...
After we obtain
the control references, we obtain the string values that we’re interested in simply
by reading their Text properties, as is shown in the following code snippets:
Visual Basic

File: AddressBook
...
vb (excerpt)

' Find the TextBox controls with updated data
Dim newAddressTextBox As TextBox = _
employeeDetails
...
FindControl("editCityTextBox")
' Extract the updated data from the TextBoxes
Dim newAddress As String = newAddressTextBox
...
Text
C#

File: AddressBook
...
cs (excerpt)

// Find the TextBox controls with updated data
TextBox newAddressTextBox =
(TextBox)employeeDetails
...
FindControl("editCityTextBox");
// Extract the updated data from the TextBoxes
string newAddress = newAddressTextBox
...
Text;

466

Updating DetailsView Records

Figure 11
...
Updating an employee’s address and city

Next, we call a stored procedure to take care of the database update
...
aspx
...
ChangeMode(DetailsViewMode
...
aspx
...
ChangeMode(DetailsViewMode
...
18
...
In these pages, we learned how to create both of these data
controls and bind data to them
...
You can use these techniques to add new records,
and update existing ones
...
We’ll also have a chance to explore the topic of code-free data
binding in that chapter
...
You learned how to use the SqlConnection class to establish a connection to the database, you learned how to use the SqlCommand
class to execute a query on a database table, and you learned how to return the
results of the command into an SqlDataReader for use within the application
...
For starters, it’s important to understand
that SqlDataReader has both advantages and disadvantages
...

❑ SqlDataReader only allows read-only, forward-only access to data
...
It doesn’t store the data locally, so after it reads one record and moves to the next one, there’s no way to go
back
...


Chapter 12: Advanced Data Access

However, SqlDataReader isn’t the only means of getting to your data, and in
many scenarios, it makes sense to use one of the two popular alternatives:
1
...
NET data source controls,
which are tightly integrated with the GridView and DetailsView controls,
and allow you to implement reading, updating, deleting, inserting, paging,
and sorting features very easily—for the most part, you don’t even need to
write any code!

2
...
This method occupies more memory on the server that runs your application, and means that fewer of Visual Web Developer’s automated features are available to you (you have to write more code!), but it does give
you more flexibility in terms of what you can do with your data
...


Using Data Source Controls
The
...

These objects enable automatic connection to various data sources, and provide
easy ways to read or modify your database using data-bound controls
...
NET data provider
...
NET 2
...
Even though the name of the
class is SqlDataSource, the fact that its name begins with Sql doesn’t meant
it works only with SQL Server—it’s really very flexible
...

❑ AccessDataSource is the data source object we use to connect to Access
databases
...

❑ XmlDataSource knows how to connect to XML files
...
We worked a little with this data source control
in Chapter 4
...
1 shows
...
1
...
aspx)
...
However, we wrote quite a bit of code to implement the viewing
and editing features for that page, and we’d need to do even more hand coding
to implement paging, sorting, and inserting features
...
This object can automate many tasks for us, and while it may not always
provide the best performance or the greatest flexibility, it’s important that we
know how to use it, because it can come in very handy for quick programming
tasks
...
aspx to a
SqlDataSource; we’ll deal with the DetailsView control later
...

Let’s start by deleting all the code in the code-behind file (AddressBooks
...
vb
or AddressBook
...
cs)
...
Leave your code-behind files
like this:
Visual Basic

File: AddressBook
...
vb (excerpt)

Imports System
...
SqlClient
Partial Class AddressBook
Inherits System
...
UI
...
aspx
...
Data;
using System
...
Collections;
using System
...
Web
...
Web
...
Web
...
WebControls;
using System
...
UI
...
WebParts;
using System
...
UI
...
Data
...
Web
...
Page
{
}

If you’re using C#, you’ll also need to delete the event handler declarations from
AddressBook
...
Remove the OnSelectedIndexChanged property from the
GridView control, and the OnModeChanging and OnItemUpdating properties from
the DetailsView control
...
aspx in Design View, and drag the SqlDataSource control
from the Toolbox (it’s located under the Data tab) onto the form
...
Of course, it will appear in the Design View, as Figure 12
...


Figure 12
...
AddressBook
...
In Source View, the code for the new
control should look like this:
File: AddressBook
...
A dialog will appear, giving us the opportunity to
provide the details of the data source
...
If we hadn’t already added the Dorknozzle
connection string to the Web
...
config
...
3
...
3
...
This is where the
fun begins!
In the next screen, we can specify the database table and the columns that we
want our data source object to handle
...
4
...
5
...
4
...
5
...
6
...
In the dialog that appears, press the Test Query button to
test that the query will work with this data source
...
6
...

Before we move on, let’s take a look at the new code we’ve added to AddressBook
...
If you switch to Source View, you’ll see that quite a bit of code has
been created for you
...
aspx (excerpt)

ConnectionString="<%$ ConnectionStrings:Dorknozzle %>"
SelectCommand="SELECT [EmployeeID], [Name], [City],
[MobilePhone] FROM [Employees] ORDER BY [Name]">


This object is amazing in its simplicity, yet the GridView can connect to it and
display the required data with very little additional effort
...


476

Binding the GridView to a SqlDataSource

In AddressBook
...
1
...
7 illustrates
...


Figure 12
...
We’re not refreshing the GridView fields

PageSize specifies the number of records the GridView should display on every
page of products
...

AllowPaging enables GridView’s paging functionality, which will cause (working)
paging links to be displayed
...


Let’s also deal with style issues by adding the line below to the skin file, SkinFile
...
The PagerStyle defines the style used by the cells that contain the
paging buttons; we’ll see these buttons in a moment
...
skin (excerpt)

GridLines="None">





CellPadding="4" GridLines="None">





Execute the project
...
8
...
8
...
)

478

Binding the DetailsView to a SqlDataSource

Binding the DetailsView to a SqlDataSource
Here, our aim is to replicate the functionality the DetailsView gave us in
Chapter 11, and to add functionality that will allow users to add and delete
employees’ records
...
aspx
...
Click its smart tag, and select Configure Data Source
...

In the first screen, choose the Dorknozzle connection string
...
Start by
specifying the Employees table and checking all of its columns, as shown in Figure 12
...


Figure 12
...
Choosing fields

479

Chapter 12: Advanced Data Access

Figure 12
...
Creating a new condition

Next, click the WHERE… button
...
For the
Control ID select grid, and leave the default value empty, as Figure 12
...

Finally, click Add, and the expression will be added to the WHERE clause list
...
Click OK to close the dialog, then click the Advanced… button
...
11
...

In the next screen, feel free to click on Test Query to ensure everything’s working
as expected
...
Enter 1 for the value, leave the type as Int32, then click OK
...
12
...

Congratulations! Your new SqlDataSource is ready to fill your DetailsView
...
Open AddressBooks
...
2
...
11
...
12
...
2
...
If you’re not using
Design View, set the columns as shown here:
File: AddressBook
...
13
...
13
...
If you don’t need inserting features, and you want to
keep the list of details short, you can simply remove the unwanted columns
from the list
...

If you agreed to let Visual Web Developer generate the DetailsView columns
for you, it will automatically have rewritten the templates we developed in the
last chapter, and added BoundField controls for each of the columns you’re
reading from the data source
...
Currently, the header
is set to display the Name field of the selected employee, which means it will be
empty when we insert a new employee (as you could see in Figure 12
...
To
change this, modify the HeaderTemplate of your DetailsView as follows:
Visual Basic

File: AddressBook
...
aspx (excerpt)


<%#Eval("Name") == null ? "Adding New Employee" :
Eval("Name")%>


IIf and the Ternary Operator
IIf (in VB) and the ternary operator (in C#) receive as parameters one
conditional expression (which returns True or False), and two values
...

In our case, the conditional expression verifies whether the Name field is
empty, which will be the case if we’re inserting a new row
...


Now, when we insert a new employee record, DetailsView will display “Adding
New Employee” in its header; when we’re editing or displaying an existing employee’s details, it will display the name of that employee, as Figure 12
...


484

Binding the DetailsView to a SqlDataSource

Figure 12
...
Adding a new employee, and displaying the new
header

One minor hitch with this solution is that the GridView isn’t instantly updated
when we make a change using the DetailsView control
...
Only after you reload the page will the data be displayed correctly by the GridView
...
To avoid this problem, we could use a simple workaround
that forces the GridView to update itself in response to the occurrence of certain
events raised by the DetailsView control
...
Use Visual Web Developer to generate the event
handlers for these events, and update the code like this:
Visual Basic

File: AddressBook
...
vb (excerpt)

Protected Sub employeeDetails_ItemUpdated( _
ByVal sender As Object, ByVal e As _

485

Chapter 12: Advanced Data Access

System
...
UI
...
DetailsViewUpdatedEventArgs) _
Handles employeeDetails
...
DataBind()
End Sub
Protected Sub employeeDetails_ItemDeleted( _
ByVal sender As Object, ByVal e As _
System
...
UI
...
DetailsViewDeletedEventArgs) _
Handles employeeDetails
...
DataBind()
End Sub
Protected Sub employeeDetails_ItemInserted( _
ByVal sender As Object, ByVal e As _
System
...
UI
...
DetailsViewInsertedEventArgs) _
Handles employeeDetails
...
DataBind()
End Sub
C#

File: AddressBook
...
cs (excerpt)

protected void employeeDetails_ItemUpdated(object sender,
DetailsViewUpdatedEventArgs e)
{
grid
...
DataBind();
}
protected void employeeDetails_ItemInserted(object sender,
DetailsViewInsertedEventArgs e)
{
grid
...

The last improvement we’ll make is to add an Add New Employee button to the
page
...


486

Binding the DetailsView to a SqlDataSource

Figure 12
...
The Add New Employee button

Add the new button above the grid like this:
File: AddressBook
...
aspx
...
EventArgs) Handles addEmployeeButton
...
ChangeMode(DetailsViewMode
...
aspx
...
ChangeMode(DetailsViewMode
...
15) will cause the DetailsView to display
in insert mode when clicked
...
Since this data source needs to
store the details of selecting, deleting, updating, and inserting rows, it looks significantly bigger than the employeesDataSource:
File: AddressBook
...
These are parameterized queries, and a data type is specified for
each of the parameters, which, as you already know, is good programming practice
...
These square brackets allow us to include spaces and
other special characters in table names
...

The SqlDataSource is the perfect tool when you need to create fully featured
forms such as the address book quickly and easily for smaller projects like the
Dorknozzle intranet
...


Displaying Lists in DetailsView
We want to improve on our DetailsView by making it show a list of departments
instead of department IDs
...
Figure 12
...


Figure 12
...
Viewing the Department drop-down list in DetailsView

Start by adding a new SqlDataSource control beside the two existing data source
controls in AddressBook
...
Name the control departmentsDataSource, click
its smart tag, and select Configure Data Source
...
Specify the Departments table and select
both of its columns, as shown in Figure 12
...

Click Next, then Finish to save the data source configuration
...
aspx (excerpt)

ConnectionString="<%$ ConnectionStrings:Dorknozzle %>"

490

Displaying Lists in DetailsView

Figure 12
...
Specifying the Departments data source

SelectCommand="SELECT [DepartmentID], [Department]
FROM [Departments]" />

Now, with AddressBook
...

Now, switch to Source View, and locate the Department ID TemplateField that
you just generated
...
aspx (excerpt)

SortExpression="DepartmentID">

Text='<%# Bind("DepartmentID") %>'>


Text='<%# Bind("DepartmentID") %>'>



491

Chapter 12: Advanced Data Access

Text='<%# Bind("DepartmentID") %>'>




Modify this generated template as highlighted below:
File: AddressBook
...
You can use that list when you’re inserting and
editing employee data—a feature that the intranet’s users are sure to find very
helpful!

More on SqlDataSource
The SqlDataSource object can make programming easier when it’s used correctly
and responsibly
...


492

More on SqlDataSource

The main advantage of your new AddressBook
...

However, embedding SQL queries right into your
...
When you’re writing real-world
applications, you’ll want to have all the data access logic centralized in specialized
classes
...

Another disadvantage of using the SqlDataSource is that its sorting and paging
features usually aren’t as fast and efficient as they could be if you used a custom
SQL query that returned the data already paged and/or sorted from the database
...
Even if
only a small subset of data needs to be shown, unless customizations are implemented, the entire table will be read from the database, and a subset of the data
displayed
...

An interesting property of SqlDataSource that’s worth noting is DataSourceMode,
whose possible values are DataSet or SqlDataReader
...
We’ll analyze the DataSet class next
...

So, what is this DataSet? The
...
0, come with
a number of objects—DataSet, DataTable, DataView, SqlDataAdapter, and
others—that provide disconnected data access
...

Both the DataSet and SqlDataReader settings of DataSourceMode have advantages and disadvantages, and the optimum approach for any task will depend on
the task itself
...


Working with Data Sets and Data Tables
We’ve been working with databases for a while now
...
Then, in the first half of

this chapter, we gained first-hand experience with the data source controls, which
can automate many features for you
...

I know that all these options can be confusing at first—you need to play around
with all of them before you can become an experienced ASP
...
Disconnected data (data that resides in memory and is completely
independent of the data source) gives us a raft of new opportunities of developing
desktop and web apps
...
Whenever we need to access data from a database,
we create a connection object and a command object
...
Figure 12
...

So, what’s the problem? Well, while being the fastest way to retrieve data from
a database, data readers can’t be used to carry out any significant work—you
can’t use them to sort, filter, or page through the data
...
18 show, data readers present a forward-only stream of data to the application: you can’t go back to a previous record, or reuse that data reader somewhere
else
...
This means that you can’t make multiple requests to a database using the
same data reader
...
Imagine a virtual database
that you’re free to use in code whenever and however you wish
...
As we’ll see in the next section, data sets have all the bells and whistles that
databases offer, including tables, columns, rows, relationships, and even queries!
A data set is a memory-resident copy of database data, so, once a data set has
been created, it can be stored in memory and its ties to the database can be
broken
...
18
...
19
...

Figure 12
...


495

Chapter 12: Advanced Data Access

Figure 12
...
Multiple pages making multiple requests from the
same data set

An even greater advantage is that data sets can be shared among multiple requests,
as illustrated in Figure 12
...

What this means is that you simply need to create the data set once per request
...

However, data sets require much more memory and resources than do data
readers
...
The
larger the amount of data kept in the data set, the more memory the data set
uses
...
This decision is important, because it
affects:
❑ resources consumed on the database server
❑ resources consumed on the application server
❑ the overall application architecture
If you’re only reading the data, using a data reader can make sense
...

This section will teach you everything you need to know to begin working with
data sets
...
The following classes will be introduced and discussed in this section:
❑ DataSet
❑ SqlDataAdapter
❑ DataTable
❑ DataColumn
❑ DataRow
❑ DataRelation
❑ DataView
We need to use most of these classes in order to work with data sets
...
The data adapter knows how to fill a DataSet with data from
the data source; it also knows how to submit to the data source any changes
you’ve made to a DataSet
...
As this class is the bridge between the database and your local data
storage objects (the other classes mentioned), it makes sense for the class to
be database-specific
...


A DataSet will always contain at least one DataTable, but it can contain many
...
If we needed to establish
a relationship between multiple DataTables within a DataSet, we’d use
DataRelations
...


497

Chapter 12: Advanced Data Access

Data Tables in ADO
...
0
The DataTable object in ADO
...
0 is more powerful than it was in
previous incarnations of the technology
...


A DataSet mirrors the structure of a relational database, as Figure 12
...


Figure 12
...
The structure of a DataSet closely resembles that
of a database

You can see the parallel between the DataSet’s structure and that of a database
...
Tables in a
database have columns and rows; our DataTables have DataColumns and DataRows
...
The major difference between DataSets and databases
is that DataSets are memory-resident, while a centralized database resides inside
a database management system
...


Binding DataSets to Controls
Now that you have some understanding of the structure of a typical DataSet,
let’s look at the process involved in creating a DataSet in code, and binding a
DataTable to a control
...
aspx
...
aspx, as you have for the other pages
in the Dorknozzle project
...
aspx (excerpt)

<%@ Page Language="VB" MasterPageFile="~/DorkNozzle
...
aspx
...
We have a blank page based on
Dorknozzle
...

Our goal through the rest of this chapter is to learn how to use the DataSet and
related objects to give life to the GridView control
...
Add references to the System
...
SqlClient
namespace (which contains the SqlDataAdapter class), and, if you’re using VB,
the System
...
Configuration namespace (which contains the
ConfigurationManager class, used for reading connection strings from
Web
...

Visual Basic

File: Departments
...
vb (excerpt)

Imports System
...
SqlClient
Imports System
...
Configuration
Partial Class Departments
Inherits System
...
UI
...
EventArgs) Handles Me
...
aspx
...
Data;
System
...
Collections;

499

Chapter 12: Advanced Data Access

using
using
using
using
using
using
using

System
...
Web
...
Web
...
Web
...
WebControls;
System
...
UI
...
WebParts;
System
...
UI
...
Data
...
Web
...
Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}

Next, we’ll add a method called BindGrid, which populates the GridView control
using an SqlDataAdapter and a DataSet
...
We assume that any postback
events won’t affect the data that’s to be displayed by the grid, so we populate
the grid just once, when the page loads
...
aspx
...
EventArgs) Handles Me
...
IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
' Define data objects
Dim conn As SqlConnection
Dim dataSet As New DataSet
Dim adapter As SqlDataAdapter
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Fill(dataSet, "Departments")

500

Binding DataSets to Controls

' Bind the grid to the DataSet
departmentsGrid
...
DataBind()
End Sub
C#

File: Departments
...
cs (excerpt)

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
// Define data objects
SqlConnection conn;
DataSet dataSet = new DataSet();
SqlDataAdapter adapter;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Fill(dataSet, "Departments");
// Bind the grid to the DataSet
departmentsGrid
...
DataBind();
}

Execute the project, and browse to your departments page, as shown in Figure 12
...

The grid is already styled, because we have a GridView skin in place
...


501

Chapter 12: Advanced Data Access

Figure 12
...
The Departments page

An SqlDataAdapter object is created in much the same way as an SqlCommand
object
...

However, it’s the line that immediately follows the creation of the adapter that
does all the work
...
The Fill method accepts two parameters: the first is the DataSet object that needs to be filled, the second is the name
of the table that we want to create within the DataSet
...

Moving on, let’s see how we can add another DataTable to our DataSet
...
Fill(dataSet, "Departments")
' Initialize the adapter with a new command
adapter
...
Fill(dataSet, "Employees")
' Bind the grid to the DataSet
departmentsGrid
...
DataMember = "Employees"
departmentsGrid
...
Fill(dataSet, "Departments");
// Initialize the adapter with a new command
adapter
...
Fill(dataSet, "Employees");
// Bind the grid to the DataSet
departmentsGrid
...
DataMember = "Employees";
departmentsGrid
...
The GridView would now appear
as shown in Figure 12
...


Figure 12
...
Displaying data from a DataTable in a GridView

503

Chapter 12: Advanced Data Access

It’s easy to imagine how quickly you could fill a page containing many GridViews
using only one DataSet as the source
...
Just like tables in a database, DataTables are built from columns and
rows
...


Implementing Paging
We saw the GridView’s paging functionality in action earlier in this chapter
...
Now that we’re binding the GridView to a
DataSet, there’s a little more work involved in getting paging up and running
...

The task of implementing paging in a GridView that has been bound to an
SqlDataAdapter is a two-step process
...
Open Departments
...
aspx (excerpt)

AllowPaging="True" PageSize="4">


Next, we need to handle the PageIndexChanging event of the GridView control
...

Double-click the PageIndexChanging entry in the Properties window, as shown
in Figure 12
...


504

Implementing Paging

Figure 12
...
Creating the PageIndexChanging event handler

Finally, fill in the generated event handler as shown below:
Visual Basic

File: Departments
...
vb (excerpt)

Protected Sub departmentsGrid_PageIndexChanging( _
ByVal sender As Object, _
ByVal e As System
...
UI
...
GridViewPageEventArgs) _
Handles departmentsGrid
...
NewPageIndex
' Set the new page index of the GridView
departmentsGrid
...
aspx
...
NewPageIndex;
// Set the new page index of the GridView
departmentsGrid
...
NewPageIndex
parameter, and used its value to set the PageIndex property of the GridView
...


505

Chapter 12: Advanced Data Access

Execute the project again
...
25 shows
...
25
...
Every time we display another page of departments in our GridView, we call the BindData method, which executes the
following code in order to retrieve a list of departments:
Visual Basic

File: Departments
...
vb (excerpt)

' Initialize connection
conn = New SqlConnection(connectionString)
' Create adapter
adapter = New SqlDataAdapter( _
"SELECT DepartmentID, Department FROM Departments", conn)
' Fill the DataSet
adapter
...
aspx
...
Fill(dataSet, "Departments");

Given that this list of departments is unlikely to change a great deal, wouldn’t it
be better if we had to query the database only once? Well, given that we now
have a complete copy of the data in the Departments table, we can! Modify the
BindGrid method as shown below:
Visual Basic

File: Departments
...
vb (excerpt)

Private Sub BindGrid()
' Define data objects
Dim conn As SqlConnection
Dim dataSet As New DataSet
Dim adapter As SqlDataAdapter
If ViewState("DepartmentsDataSet") Is Nothing Then
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Fill(dataSet, "Departments")
' Store the DataSet in view state
ViewState("DepartmentsDataSet") = dataSet
Else
dataSet = ViewState("DepartmentsDataSet")
End If
' Bind the grid to the DataSet
departmentsGrid
...
DataBind()
End Sub

507

Chapter 12: Advanced Data Access

C#

File: Departments
...
cs (excerpt)

private void BindGrid()
{
// Define data objects
SqlConnection conn;
DataSet dataSet = new DataSet();
SqlDataAdapter adapter;
if(ViewState["DepartmentsDataSet"] == null)
{
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Fill(dataSet, "Departments");
// Store the DataSet in view state
ViewState["DepartmentsDataSet"] = dataSet;
}
else
{
dataSet = (DataSet)ViewState["DepartmentsDataSet"];
}
// Bind the grid to the DataSet
departmentsGrid
...
DataBind();
}

Here, we’re using the ViewState collection to store our DataSet
...
If the users navigate away from this
page, the data in ViewState will be lost—even if they return to the page within
the same session
...
If no such item exists, we create a new
DataSet, fill it with data from the database, as before, and store it in ViewState
...
Regardless of how the DataSet is
loaded, we bind it to our GridView as we did before
...


Implementing Sorting
To implement sorting functionality, we need to understand a few details of the
inner workings of data binding
...
However, by virtue of the fact that your DataSet has only
contained a single DataTable, the GridView control has been smart enough to
figure out that what you probably meant was the following:
Visual Basic

' Bind the grid to the DataSet
departmentsGrid
...
Tables("Departments")
departmentsGrid
...
DataSource = dataSet
...
DataBind();

However, this isn’t technically correct in the strictest sense, either
...
Thankfully,
each DataTable has a DefaultView property, which the GridView will automatically use whenever you bind it to a DataTable
...
DataSource = _
dataSet
...
DefaultView
departmentsGrid
...
DataSource =

509

Chapter 12: Advanced Data Access

dataSet
...
DefaultView;
departmentsGrid
...

DataViews represent a customized view of a DataSet for sorting, filtering,
searching, editing, and navigation
...
However, if we want to enable sorting, we need to access
the DataView and set its sorting parameters
...

When we do that, the grid’s column headings become hyperlinks
...

Set the AllowSorting property of the GridView control in Departments
...
Then, complete the code as shown:
Visual Basic

File: Departments
...
vb (excerpt)

Protected Sub departmentsGrid_Sorting(ByVal sender As Object, _
ByVal e As System
...
UI
...
GridViewSortEventArgs) _
Handles departmentsGrid
...
SortExpression
' Decide and save the new sort direction
If (sortExpression = gridSortExpression) Then
If gridSortDirection = SortDirection
...
Descending
Else
gridSortDirection = SortDirection
...
SortDirection
...
Ascending
End If
' Return the state
Return ViewState("GridSortDirection")
End Get
Set(ByVal value)
ViewState("GridSortDirection") = value
End Set
End Property
Private Property gridSortExpression()
Get
' Initial sort expression is DepartmentID
If (ViewState("GridSortExpression") Is Nothing) Then
ViewState("GridSortExpression") = "DepartmentID"
End If
' Return the sort expression
Return ViewState("GridSortExpression")
End Get
Set(ByVal value)
ViewState("GridSortExpression") = value
End Set
End Property
C#

File: Departments
...
cs (excerpt)

protected void departmentsGrid_Sorting(object sender,
GridViewSortEventArgs e)
{
// Retrieve the name of the clicked column (sort expression)
string sortExpression = e
...
Ascending)
{
gridSortDirection = SortDirection
...
Ascending;
}
}
else

511

Chapter 12: Advanced Data Access

{
gridSortDirection = SortDirection
...
Ascending;
}
// Return the state
return (SortDirection) ViewState["GridSortDirection"];
}
set
{
ViewState["GridSortDirection"] = value;
}
}
private string gridSortExpression
{
get
{
// Initial sort expression is DepartmentID
if (ViewState["GridSortExpression"] == null)
{
ViewState["GridSortExpression"] = "DepartmentID";
}
// Return the sort expression
return (string) ViewState["GridSortExpression"];
}
set
{
ViewState["GridSortExpression"] = value;
}
}

512

Implementing Sorting

Properties
We haven’t really discussed the task of defining your own properties since
Chapter 4, so now might be a good time for a quick refresher
...
You’ve already dealt with quite a few of that class’s features, such as
its Load event and its IsPostBack property
...
When you read data from a property,
its Get code is executed
...
In the same way, when a
value is written to a property, its Set code is executed, which can also be
quite complex if you choose to make it so
...
aspx
...
config
Dim connectionString As String = _
ConfigurationManager
...
ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
' Create adapter
adapter = New SqlDataAdapter( _
"SELECT DepartmentID, Department FROM Departments", _
conn)
' Fill the DataSet
adapter
...
Ascending Then

513

Chapter 12: Advanced Data Access

sortExpression = gridSortExpression & " ASC"
Else
sortExpression = gridSortExpression & " DESC"
End If
' Sort the data
dataSet
...
DefaultView
...
DataSource = _
dataSet
...
DefaultView
departmentsGrid
...
aspx
...
config
string connectionString =
ConfigurationManager
...
ConnectionString;
// Initialize connection
conn = new SqlConnection(connectionString);
// Create adapter
adapter = new SqlDataAdapter(
"SELECT DepartmentID, Department FROM Departments",
conn);
// Fill the DataSet
adapter
...
Ascending)
{
sortExpression = gridSortExpression + " ASC";

514

Implementing Sorting

}
else
{
sortExpression = gridSortExpression + " DESC";
}
// Sort the data
dataSet
...
DefaultView
...
DataSource =
dataSet
...
DefaultView;
departmentsGrid
...
26
...
26
...

In order to sort the data in the grid, all we need to do is set the Sort property of
the view we’re displaying to ColumnNameSortOrder, where ColumnName is, of
course, the name of the column we’re sorting, and SortOrder is either ASC (for

515

Chapter 12: Advanced Data Access

ascending) or DESC (for descending)
...

This property must be set before the data binding is performed, as is shown in
the following code, which will sort the data by DepartmentID in descending numeric order:
Visual Basic

dataTable
...
Sort = "DepartmentID DESC"
departmentsGrid
...
DefaultView
departmentsGrid
...
DefaultView
...
DataSource = dataTable
...
DataBind();

It’s a pretty simple task to sort a DataView in code like this, but if we want to
let users sort the data on the basis of any column, in any direction, things get a
little bit more complicated
...

In order to be truly user-friendly, our grid should behave like this:
❑ The first time a column header is clicked, the grid should sort the data in ascending order, based on that column
...

When a column heading is clicked, the grid’s Sorting event is fired
...
Ascending or SortDirection
...
aspx
...
Ascending Then
sortExpression = gridSortExpression & " ASC"
Else
sortExpression = gridSortExpression & " DESC"
End If
C#

File: Departments
...
cs (excerpt)

// Prepare the sort expression using the gridSortDirection and
// gridSortExpression properties
string sortExpression;
if(gridSortDirection == SortDirection
...
That’s what the properties
gridSortExpression and gridSortDirection do:
Visual Basic

File: Departments
...
vb (excerpt)

Private Property gridSortDirection()
Get
' Initial state is Ascending
If (ViewState("GridSortDirection") Is Nothing) Then
ViewState("GridSortDirection") = SortDirection
...
aspx
...
Ascending;
}
// Return the state
return (SortDirection) ViewState["GridSortDirection"];
}
set
{
ViewState["GridSortDirection"] = value;
}
}
private string gridSortExpression
{
get
{
// Initial sort expression is DepartmentID
if (ViewState["GridSortExpression"] == null)
{
ViewState["GridSortExpression"] = "DepartmentID";
}
// Return the sort expression
return (string) ViewState["GridSortExpression"];
}
set
{
ViewState["GridSortExpression"] = value;
}
}

518

Implementing Sorting

Here, we use the ViewState collection to store information about which column
is being sorted, and the direction in which it’s being sorted
...
The method starts by retrieving the name of the
clicked column:
Visual Basic

File: Departments
...
vb (excerpt)

Protected Sub departmentsGrid_Sorting(ByVal sender As Object, _
ByVal e As System
...
UI
...
GridViewSortEventArgs) _
Handles departmentsGrid
...
SortExpression
C#

File: Departments
...
cs (excerpt)

protected void departmentsGrid_Sorting(object sender,
GridViewSortEventArgs e)
{
// Retrieve the name of the clicked column (sort expression)
string sortExpression = e
...
If it is, we need to toggle the sorting direction
...
aspx
...
Ascending Then
gridSortDirection = SortDirection
...
Ascending
End If
Else
gridSortDirection = WebControls
...
Ascending
End If
C#

File: Departments
...
cs (excerpt)

// Decide and save the new sort direction
if (sortExpression == gridSortExpression)
{
if(gridSortDirection == SortDirection
...
Descending;
}

519

Chapter 12: Advanced Data Access

else
{
gridSortDirection = SortDirection
...
Ascending;
}

Finally, we save the new sort expression to the gridSortExpression property,
whose value will be retained in case the user keeps working (and changing sort
modes) on the page:
Visual Basic

File: Departments
...
vb (excerpt)

' Save the new sort expression
gridSortExpression = sortExpression
' Rebind the grid to its data source
BindGrid()
C#

File: Departments
...
cs (excerpt)

// Save the new sort expression
gridSortExpression = sortExpression;
// Rebind the grid to its data source
BindGrid();

After we store the sort expression, we rebind the grid to its data source so that
the expression will reflect the changes we’ve made to the gridSortExpression
and gridSortDirection properties
...
Normally you’d have to apply WHERE
clauses to filter the data before it reaches your application, but in certain cases
you may prefer to filter data on the client
...
You could retrieve the complete list of employees or
departments from the database using a single request, then let the user filter the
list locally
...
For instance,
the following filter selects all departments whose names start with “a”:
Visual Basic

dataTable
...
RowFilter = "Department LIKE 'a%'"
C#

dataTable
...
RowFilter = "Department LIKE 'a%'";

Updating a Database from a Modified
DataSet
So far, we’ve used the DataSet exclusively for retrieving and binding database
data to controls such as the GridView
...

The SqlDataAdapter has the following four properties, which represent the main
database commands:
❑ SelectCommand
❑ InsertCommand
❑ UpdateCommand
❑ DeleteCommand
The SelectCommand contains the command that’s executed when we call Fill
...

If we want to insert, update, or remove records in a database, we simply make
modifications to the data in the DataSet or DataTable, then call the Update
method of the SqlDataAdapter
...

The excellent news is that ADO
...


521

Chapter 12: Advanced Data Access

Basically, we just need to populate the DataSet or DataTable objects (usually
by performing a SELECT query), then use SqlDataAdapter and SqlCommandBuilder
to do the rest of the work for us
...
The new lines are highlighted (note that I’ve simplified BindGrid by removing the code that stores and
retrieves the DataSet from view state, as well as the code that sorts the results):
Visual Basic

Private Sub BindGrid()
' Define data objects
Dim conn As SqlConnection
Dim dataSet As New DataSet
Dim adapter As SqlDataAdapter
Dim dataRow As DataRow
Dim commandBuilder As SqlCommandBuilder
' Read the connection string from Web
...
ConnectionStrings( _
"Dorknozzle")
...
Fill(dataSet, "Departments")
' Make changes to the table
dataRow = dataSet
...
NewRow()
dataRow("Department") = "New Department"
dataSet
...
Rows
...
Update(dataSet
...
DataSource = _
dataSet
...
DefaultView
departmentsGrid
...
config
string connectionString =
ConfigurationManager
...
ConnectionString;
// Initialize connection
conn = new SqlConnection(connectionString);
// Create adapter
adapter = new SqlDataAdapter(
"SELECT DepartmentID, Department FROM Departments",
conn);
// Fill the DataSet
adapter
...
Tables["Departments"]
...
Tables["Departments"]
...
Add(dataRow);
// Submit the changes
commandBuilder = new SqlCommandBuilder(adapter);
adapter
...
Tables["Departments"]);
departmentsGrid
...
Tables["Departments"];
departmentsGrid
...
27
...
The work that’s required to
submit the changes to the database requires us to write just two rows of code
...

We create an SqlCommandBuilder object, passing in our SqlDataAdapter
...
Having done this, SqlCommandBuilder generates the necessary
SQL queries and stores them in the SqlDataAdapter for the Update method to
use
...


523

Chapter 12: Advanced Data Access

Figure 12
...
Adding many new departments

Deleting all of these new departments is also an easy task
...
config
Dim connectionString As String = _
ConfigurationManager
...
ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
' Create adapter
adapter = New SqlDataAdapter( _
"SELECT DepartmentID, Department FROM Departments", _
conn)
' Fill the DataSet

524

Updating a Database from a Modified DataSet

adapter
...
Tables("Departments")
...
Delete()
End If
Next
' Submit the changes
commandBuilder = New SqlCommandBuilder(adapter)
adapter
...
Tables("Departments"))
' Bind the grid to the DataSet
departmentsGrid
...
Tables("Departments")
...
DataBind()

Note that in the C# version the conversion to string needs to be performed explicitly:
C#

// Define data objects
SqlConnection conn;
DataSet dataSet = new DataSet();
SqlDataAdapter adapter;
SqlCommandBuilder commandBuilder;
// Read the connection string from Web
...
ConnectionStrings[
"Dorknozzle"]
...
Fill(dataSet, "Departments");
// Make changes to the table
foreach (DataRow dataRow in dataSet
...
Rows)
{
if(dataRow["Department"]
...
Delete();
}
}
// Submit the changes
commandBuilder = new SqlCommandBuilder(adapter);
adapter
...
Tables["Departments"]);

525

Chapter 12: Advanced Data Access

departmentsGrid
...
Tables["Departments"];
departmentsGrid
...


Summary
This chapter has given us the chance to explore some more important concepts
of ADO
...
First, you learned about the data source controls, and how they
can be used to build code-free data binding
...
We then moved on to learn about the constructs of DataSets, including DataTables and DataViews
...
Finally, we looked at sorting, paging, and filtering data using
DataViews, and updated a data source from a modified DataSet using the
SqlCommandBuilder
...
NET’s security features
...
NET’s form-based security capabilities, we’ll learn how to restrict each user’s
access to the specific web forms we want them to be able to use, while still allowing
public access to other parts of the site
...


526

13

Security and User Authentication

The issue of security is important in many facets of information technology, but
it’s especially relevant in web development
...

One common approach is to have visitors to your site log in before they can view
certain pages; another is to ensure that restricted pages cannot be accessed simply
by typing in the appropriate URLs, unless the user has been specifically allowed
to view those pages
...

In this chapter, we’ll learn some simple coding techniques and discover just how
easy it is to secure your web applications using ASP
...
As with many other
chapters, this one contains many goodies that will be new to existing ASP
...
0 and 1
...
NET 2
...

Security is a huge topic, and several books have been written on the subject
...
NET 2
...


Basic Security Guidelines
The primary and most important element of building secure applications is to
consider and plan an application’s security from the early stages of its development
...
Generally speaking, ASP
...

Back in Chapter 6, you learned how to use validation controls to enable the
client-side validation of user input, and how to double-check that validation
on the server side
...
The submission of bad or corrupted data can generate
errors in your web application, and compromise its security
...

The database is quite often the most important asset we need to protect—after
all, it’s here that most of the information our application relies upon is stored
...
If the app builds SQL commands by naively assembling text strings that include data received from user input, an attacker can
alter the meaning of the commands the application produces simply by including malicious code in the user input
...
NET to make use of command
parameters, and parameterized stored procedures, in order to include user
input in SQL queries
...
NET has built-in protection against
injection attacks
...
NET will throw an exception in cases where the input parameter
doesn’t match the expected data type
...
unixwiz
...
html
...

Assuming your web application produces HTML output, you should always
bear in mind that any text you include in that output will also be interpreted
as HTML by your visitors’ browsers
...
HtmlEncode
method
...
If that user input were to contain HTML code, that
code might disrupt the appearance or functionality of your application when
it was displayed
...
HtmlEncode("


Writing to Text Files



Write the following text within a text file:


OnClick="WriteText" />




As you can see, we import the System
...
Next, we add a TextBox control to
handle collection of the user-entered text, and a Button control to send the information to the server for processing
...
This method will write the contents of the
TextBox to the text file:

576

Writing Content to a Text File

Visual Basic

File: WriteFile
...
CreateText( _
"C:\WebDocs\Learning\myText
...
WriteLine(myText
...
aspx (excerpt)



Apart from the new Using construct, the code is pretty straightforward
...
To obtain the variable’s
value, we call the CreateText method of the File class, passing in the location
of the text file, which returns a new StreamWriter
...

What about Using, then? Similarly to database connections, streams are something that we need to close when we’re done working with them, so they don’t
occupy resources unnecessarily
...


Disposing of Objects
Technically, when we work with Using, the object is disposed of, rather
than simply closed
...

When the code enclosed by Using finishes executing, streamWriter’s
Dispose method is called automatically for you
...


577

Chapter 14: Working with Files and Email

In the world of
...
NET’s Garbage Collector, but for classes that support the
Dispose method (such as StreamWriter), you can use this method (or
the Using construct) to remove an object from memory immediately
...
Normally, when we need to call a method of a particular class,
we create an object of that class first
...
Shared or static methods can be called without
our having to create an actual instance of the class
...

We worked with shared/static class members earlier, when we read the connection
string
...
ConnectionStrings( _
"Dorknozzle")
...
Instance methods are
most commonly used, but shared/static methods can be useful for providing
generic functionality that doesn’t need to be tied to a particular class instance
...
Initially, all you’ll see is an interface similar
to Figure 14
...

Type some text into the text box, and click the Write button to submit your text
for processing
...
txt file in Notepad, and as in
Figure 14
...

If you try to enter a different value into the TextBox control and click the Write
button, the existing text will be overwritten with the new content
...
As Figure 14
...


578

Writing Content to a Text File

Figure 14
...
Writing text to a file

Figure 14
...
Viewing your new file in Notepad

Figure 14
...
Appending text

Also note that, rather than specifying the full path to the text file, you can use
the MapPath method to generate the full path to the text file automatically
...
aspx (excerpt)

Using streamWriter As StreamWriter = File
...
txt"))

579

Chapter 14: Working with Files and Email

C#

File: WriteFile
...
AppendText(
MapPath("myText
...


Reading Content from a Text File
Just as you used the CreateText and AppendText methods of the File class to
return a new StreamWriter object, you can use the OpenText method of the File
class to return a new StreamReader
...

To experiment with the process of reading from text files, create a new web form
named ReadFile
...
aspx, and
add this code to it:
Visual Basic

File: ReadFile
...
IO" %>
...
w3
...
dtd">



Reading from Text Files



OnClick="ReadText" />







As you can see, we’ve simply added a Button and Label to the page
...
Let’s add this method next
...
aspx (excerpt)


C#

File: ReadFile
...
Text = "";
using (StreamReader streamReader =
File
...
txt")))
{
inputString = streamReader
...
Text += inputString + "
";
inputString = streamReader
...
Next, we set the text value of the Label control to an empty
string
...

The next thing our method has to do is call the OpenText method of the File
class to return a new StreamReader, again passing in the full path to the text file
...


581

Chapter 14: Working with Files and Email

Visual Basic

File: ReadFile
...
OpenText(MapPath("myText
...
aspx (excerpt)

using (StreamReader streamReader =
File
...
txt")))
{

Next, we call the ReadLine method of the streamReader object to get the first
line of the file:
Visual Basic

File: ReadFile
...
ReadLine()
C#

File: ReadFile
...
ReadLine();

Now we loop through the file, reading each line and adding it, in turn, to the end
of the text in the Label:
Visual Basic

File: ReadFile
...
Text &= inputString & "
"
inputString = streamReader
...
aspx (excerpt)

while (inputString != null)
{
resultLabel
...
ReadLine();
}

Remember, While loops are used when you want to repeat the loop while a condition remains True
...
Within the loop, we simply
append the value of inputString to the Label control’s Text property using the
&= operator (+= in C#), then read the next line from streamReader into
inputString
...
Figure 14
...
aspx
...
7
...
The classes
that are available in the System
...
The DirectoryInfo class, on the
other hand, requires instantiation, as it contains only instance methods
...
In the same Learning folder, create a web
form named Directories
...
aspx (excerpt)

<%@ Import Namespace="System
...
0 Transitional//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-transitional
...
w3
...

When a user selects an item from the DropDownList control, the SelectedIndexChanged event is raised, and ViewDriveInfo is called
...
aspx (excerpt)



Initially, we create a new string variable and set it equal to the full path of the
text file:
Visual Basic

File: PathInfo
...
txt")

Next, we write into the Label control the complete file path, filename with extension, directory, extension, and filename without extension, by using the Path
class’s
GetFileName,
GetDirectoryName,
GetExtension,
and
GetFileNameWithoutExtension methods, respectively
...
Figure 14
...


Figure 14
...
Retrieving the path, filename, directory, file
extension, and filename without extension for the text file

588

Working with Directory and File Paths

However, those aren’t the only methods to which the Path class gives us access
...
NET Framework SDK documentation for full details on all of these
methods
...
For example, you could create a photo album
site to which users could upload images for others to view
...
NET 2
...
The FileUpload control can be found
in the Standard tab of the Toolbox; Figure 14
...


Figure 14
...
The FileUpload control in Visual Web Developer

The FileUpload control has the following read-only properties:
HasFile
True if the user has uploaded a file, False otherwise
FileName

the name of the file as a string
FileContent

a stream that can be used to read the contents of the file
FileBytes

an array of bytes that can be used to read the contents of the file
PostedFile
an HttpPostedFile object for the uploaded file; this object has properties

that can be used to obtain additional data about the file, such as:
ContentLength

590

the file length in bytes

Uploading Files

ContentType

the MIME type of the file (such as image/gif for a GIF
file)1

The FileUpload control also has a method that you’ll find very useful: SaveAs
...
The SaveAs method takes as a parameter a string containing
the path and the name of the target file
...
Create a new web form named FileUpload
...
aspx (excerpt)

<%@ Page Language="VB" %>
<%@ Import Namespace="System
...
0 Transitional//EN"
"http://www
...
org/TR/xhtml1/DTD/xhtml1-transitional
...
HasFile Then
' Get the name of the file
Dim fileName As String = fileUpload
...
SaveAs(MapPath(fileName))
' Inform the user about the file upload success
label
...
"
Else
label
...
w3
...
w3schools
...
asp
...


591

Chapter 14: Working with Files and Email








If you’re using C#, you should place the following code in the


Sending Emails with ASP<br> ...<br> <br /><br />598<br /><br /> Sending a Test Email<br /><br />Visual Basic<br /><br />File: SendEmail<br> ...<br> ro", "From Cristian Test")<br />Dim toAddress As New MailAddress( _<br />"contact@cristiandarie<br> ...<br> From = fromAddress<br />message<br> ...<br> Add(toAddress)<br />message<br> ...<br> Body = "This is the body of a sample message"<br />' Set server details<br />smtpClient<br> ...<br> Credentials = _<br />'<br />New System<br> ...<br> NetworkCredential("user", "password")<br />' Send the email<br />smtpClient<br> ...<br> Text = "Email sent<br> ...<br> Text = "Coudn't send the message!"<br />End Try<br />End Sub<br /></script><br />C#<br /><br />File: SendEmail<br> ...<br> ro", "From Cristian Test");<br />MailAddress toAddress = new MailAddress(<br />"contact@cristiandarie<br> ...<br> From = fromAddress;<br />message<br> ...<br> Add(toAddress);<br />message<br> ...<br> Body = "This is the body of a sample message";<br />// Set server details<br />smtpClient<br> ...<br> Credentials = new System<br> ...<br> NetworkCredential(<br />//<br />"user", "password");<br />// Send the email<br />smtpClient<br> ...<br> Text = "Email sent<br> ...<br> Text = "Coudn't send the message!";<br />}<br />}<br /></script><br /><br />Execute the script, and press the Send Email button, as shown in Figure 14<br> ...<br> <br /><br />Figure 14<br> ...<br> Sending the email<br /><br />The email should arrive successfully at its destination, looking something like<br />Figure 14<br> ...<br> <br />Now you’re ready to update the Dorknozzle site!<br /><br />600<br /><br /> Creating the Company Newsletter Page<br /><br />Figure 14<br> ...<br> Viewing the email<br /><br />Creating the Company Newsletter Page<br />Let’s now extend the Dorknozzle site structure by adding a Newsletters page<br> ...<br> <br />Open the Dorknozzle project in Visual Web Developer, and add to it a new web<br />form named AdminNewsletter<br> ...<br> When prompted, select<br />the Dorknozzle<br> ...<br> <br />Complete the generated code like this:<br />File: AdminNewsletter<br> ...<br> master"<br />AutoEventWireup="false" CodeFile="AdminNewsletter<br> ...<br> vb"<br />Inherits="AdminNewsletter" Title="Dorknozzle Admin Newsletter"<br />%><br /><asp:Content ID="Content1"<br />ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"><br /><h1>Create Newsletter</h1><br /><asp:Label ID="resultLabel" runat="server" ForeColor="Red"/><br /><br />To:<br /><br /><asp:TextBox ID="toTextBox" runat="server" /><br /><br />Subject:<br /><br /><asp:TextBox ID="subjectTextBox" runat="server" /><br /><br />Introduction:<br /><br /><br />601<br /><br /> Chapter 14: Working with Files and Email<br /><br /><asp:TextBox ID="introTextBox" runat="server"<br />TextMode="MultiLine" Width="300" Height="100" /><br /><br />Employee Of The Month:<br /><br /><asp:TextBox ID="employeeTextBox" runat="server" /><br /><br />Featured Event:<br /><br /><asp:TextBox ID="eventTextBox" runat="server" /><br /><br /><br /><asp:Button ID="sendNewsletterButton" runat="server"<br />Text="Send Newsletter" /><br /></asp:Content><br /><br />Switch to Design View<br> ...<br> 18<br> ...<br> The boxes will allow the administrator to specify who the email is to be<br />sent to and what the subject is, enter a simple introduction, identify the employee<br />of the month, and feature a company event and a store item<br> ...<br> <br />To ensure that only administrators can send email messages, add the code highlighted in bold below, which we discussed in detail in Chapter 13, to Web<br> ...<br> config (excerpt)<br /><br /><!-- Only administrators are allowed to access<br />AdminTools<br> ...<br> aspx"><br /><system<br> ...<br> web><br /></location><br /><!-- Only administrators are allowed to send emails --><br /><location path="AdminNewsletter<br> ...<br> web><br /><authorization><br /><allow roles="Administrators" /><br /><deny users="*" /><br /></authorization><br /></system<br> ...<br> 18<br> ...<br> We can use either of two<br />approaches to solve this problem:<br />❑ Host the image on our web server and reference it in an <img> tag in the<br />HTML code of the message (e<br> ...<br> <img src="http://www<br> ...<br> com/Images/Newsletter<br> ...<br> <br />❑ Embed the image data in the email<br> ...<br> If you want readers to see the image even when<br />they’re not connected to the Internet, you should look into the second option<br> ...<br> 3<br />All we need to do is handle the Send Newsletter button’s Click event<br> ...<br> In<br />the code-behind file, we’ll need to import the System<br> ...<br> Mail namespace:<br />Visual Basic<br /><br />File: AdminNewsletter<br> ...<br> vb (excerpt)<br /><br />Imports System<br> ...<br> Mail<br />C#<br /><br />File: AdminNewsletter<br> ...<br> cs (excerpt)<br /><br />using System<br> ...<br> Mail;<br /><br />Then, complete the code of sendNewsletterButton_Click to send your newsletter:<br />Visual Basic<br /><br />File: AdminNewsletter<br> ...<br> vb (excerpt)<br /><br />Protected Sub sendNewsletterButton_Click( _<br />ByVal sender As Object, ByVal e As System<br> ...<br> Click<br />Dim smtpClient As SmtpClient = New SmtpClient()<br />Dim message As MailMessage = New MailMessage()<br />' Try to send the message<br />Try<br />' Prepare two email addresses<br />Dim fromAddress As New MailAddress( _<br />"newsletter@dorknozzle<br> ...<br> Text)<br />' Prepare the mail message<br />message<br> ...<br> To<br> ...<br> Subject = subjectTextBox<br> ...<br> IsBodyHtml = True<br />message<br> ...<br> HtmlEncode(subjectTextBox<br> ...<br> cristiandarie<br> ...<br> gif"" />" & _<br />"<p>" & _<br />HttpUtility<br> ...<br> Text) & "</p>" & _<br />"<p>Employee of the month: " & _<br />HttpUtility<br> ...<br> Text) & "</p>" & _<br />3<br /><br />604<br /><br />http://www<br> ...<br> com/blog/DisplayBlog<br> ...<br> HtmlEncode(eventTextBox<br> ...<br> Host = "localhost"<br />' Send the email<br />smtpClient<br> ...<br> Text = "Email sent!<br />"<br />Catch ex As Exception<br />' Display error message<br />resultLabel<br> ...<br> aspx<br> ...<br> com", "Your Friends at Dorknozzle"<br />);<br />MailAddress toAddress = new MailAddress(toTextBox<br> ...<br> From = fromAddress;<br />message<br> ...<br> Add(toAddress);<br />message<br> ...<br> Text;<br />message<br> ...<br> Body =<br />"<html><head><title>" +<br />HttpUtility<br> ...<br> Text) +<br />"" +
" ...
ro/Dorknozzle" +
"/Images/newsletter_header
...
HtmlEncode(introTextBox
...
HtmlEncode(employeeTextBox
...
HtmlEncode(eventTextBox
...
Host = "localhost";
// Send the email
smtpClient
...
Text = "Email sent!
";
}
catch (Exception ex)
{
// Display error message
resultLabel
...
Initially, we create a
new instance of the MailMessage class, called message:
Visual Basic

File: AdminNewsletter
...
vb (excerpt)

Dim message As MailMessage = New MailMessage()
C#

File: AdminNewsletter
...
cs (excerpt)

MailMessage message = new MailMessage();

Next, we begin to define the email message by setting some of the properties that
the MailMessage class exposes:
Visual Basic

File: AdminNewsletter
...
vb (excerpt)

' Prepare two email addresses
Dim fromAddress As New MailAddress( _
"newsletter@dorknozzle
...
Text)
' Prepare the mail message
message
...
To
...
Subject = subjectTextBox
...
IsBodyHtml = True
C#

File: AdminNewsletter
...
cs (excerpt)

// Prepare two email addresses
MailAddress fromAddress = new MailAddress(
"newsletter@dorknozzle
...
Text);
// Prepare the mail message

606

Creating the Company Newsletter Page

message
...
To
...
Subject = subjectTextBox
...
IsBodyHtml = true;

You’ll notice we’ve set the IsBodyHtml property to True because we’re creating
an HTML email message
...

Next, we need to create the body of the message, which, essentially, will be an
HTML document:
Visual Basic

File: AdminNewsletter
...
vb (excerpt)

message
...
HtmlEncode(subjectTextBox
...
cristiandarie
...
gif"" />" & _
"

" & _
HttpUtility
...
Text) & "

" & _
"

Employee of the month: " & _
HttpUtility
...
Text) & "

" & _
"

This month's featured event: " & _
HttpUtility
...
Text) & "

" & _
""
C#

File: AdminNewsletter
...
cs (excerpt)

message
...
HtmlEncode(subjectTextBox
...
cristiandarie
...
gif\" />" +
"

" +
HttpUtility
...
Text) + "

" +
"

Employee of the month: " +
HttpUtility
...
Text) + "

" +
"

This month's featured event: " +
HttpUtility
...
Text) + "

" +
"";

As we’re building an HTML document, we need to take care to convert special
characters (including <, >, and &) into their character entity equivalents (<,
>, &, and so on)
...


607

Chapter 14: Working with Files and Email

Also note that the image we’ll use in the email has to be hosted on a site somewhere
...
To get this example to work
properly, you’ll need to host the image on your web site, and use the appropriate
URL in your code
...
NET server should also act as our outgoing
mail server—you’ll need to change this if you’re using another SMTP server
...
aspx (excerpt)

' Set server details
smtpClient
...
Send(message)
' Inform the user
resultLabel
...
aspx (excerpt)

// Set server details
smtpClient
...
Send(message);
// Inform the user
resultLabel
...
Enter all the necessary information into the newsletter page and click the Send Newsletter button, as shown in
Figure 14
...


608

Creating the Company Newsletter Page

Figure 14
...
Sending the newsletter

609

Chapter 14: Working with Files and Email

Figure 14
...
Receiving the newsletter

You should receive the “Email sent!” message once the email is sent
...
The message should look like the one
shown in Figure 14
...


Summary
This chapter introduced you to some important topics and gave you the ability
to read and write to files, access directory information, upload files from the client
to the server, and send email messages in ASP
...

The topics we covered in this chapter will prove invaluable as you develop applications with ASP
...
Although, strictly speaking, they’re not core features of
ASP
...
NET applications
...

I’ve grouped the lists of controls on the basis of their locations within the Toolbox:
❑ standard controls
❑ validation controls
❑ navigation controls
❑ HTML server controls
As all the web controls listed here are based on (or, more specifically, derived
from) the WebControl class, they inherit its properties and methods
...


The WebControl Class
Properties
AccessKey

specifies a shortcut key that quickly selects a control
without the user needing to use a mouse; the shortcut
command is usually Alt plus a letter or number

Attributes

allows the accessing and manipulation of the attributes
of the HTML code rendered by the control

BackColor

the control’s current background color

BorderColor

color for the border

BorderStyle

style of border drawn around the web control; default
is NotSet; other values are None, Solid, Double,
Groove, Ridge, Dotted, Dashed, Inset, and Outset

Appendix A: Web Control Reference

BorderWidth

width of the border

Controls

a collection of all the controls contained within the
web control (its child controls)

CssClass

indicates the style class within the current CSS style
sheet that should be applied to the web control

Enabled

determines whether the web control is active and able
to receive user input

EnableTheming

determines whether the control uses themes

Font

a FontInfo object representing the control’s current
font
Properties of FontInfo include Bold, Italic, Name,
Names, Overline, Size, Strikeout, and Underline
...
These are listed in the following
sections
...
), LowerAlpha (a, b, c,
...
), LowerRoman (i, ii, iii,
...
),
Circle, CustomImage, Disc, and Square

613

Appendix A: Web Control Reference

DisplayMode

determines the display mode, which can be Text (the
default), or HyperLink (if you want the list to be
formed of links)

FirstBulletNumber

specifies the value of the first bullet

SelectedIndex

the index of the selected item

SelectedItem

the currently selected item as a ListItem object

SelectedValue

the Value of the selected ListItem object

Target

specifies the target window or frame in which new
content should be displayed when a link is clicked;
possible values are _blank, _parent, _search, _self,
and _top

Text

the text of the BulletedList control

Events
Click

raised when the Button is clicked and the form is submitted to the server for processing

Button
Properties
CommandName

CommandArgument

passes a value to the Command event when the Button
is clicked

CausesValidation

allows interaction with client-side validation controls;
when False, validation does not occur

Text

specifies the text displayed by the Button

Visible

614

passes a value to the Command event when the Button
is clicked

controls the visibility of the Button

Calendar

Events
Click

raised when the Button is clicked and the form is submitted to the server for processing

Command

raised when the Button is clicked and the form is submitted to the server for processing; passes the values
of the CommandName and CommandArgument properties

Calendar
Properties
CellPadding

specifies the number of pixels between a cell and its
border

CellSpacing

specifies the number of pixels between cells

DayHeaderStyle

specifies the style of the weekdays listed at the top of
the calendar

DayNameFormat

sets the format of day names; possible values are
FirstLetter, FirstTwoLetters, Full, and Short
...


Visible

controls the visibility of the Panel

PlaceHolder
Properties
Visible

controls the visibility of the PlaceHolder

RadioButton
Properties
AutoPostBack

automatically

posts

the

form

containing

the

RadioButton whenever checked or unchecked is True
Checked

shows the RadioButton as checked if set to True

GroupName

determines the name of the group to which the
RadioButton belongs

Text

specifies the text displayed next to the RadioButton

625

Appendix A: Web Control Reference

TextAlign

determines

how

the

text

associated

with

the

RadioButton is aligned; possible values are Left and
Right

Events
CheckedChanged

raised when the RadioButton is checked or unchecked

RadioButtonList
Properties
AutoPostBack

automatically

posts

the

form

containing

the

RadioButtonList whenever checked or unchecked is
True
DataMember

represents the particular table within the data source

DataSource

represents the actual data source to use when binding
to a RadioButtonList

DataTextField

represents the field within the data source to use with
the RadioButtonList’s text label

DataTextFormatString

specifies a format string that determines how the
RadioButtonList is displayed

DataValueField

represents the field within the data source to use with
the RadioButtonList’s value

RepeatColumns

the collection of items within the RadioButtonList

Items

determines the number of columns to use when displaying the radio buttons

RepeatDirection

indicates the direction in which the radio buttons
should repeat; possible values are Horizontal and
Vertical

RepeatLayout

626

determines how the radio buttons should repeat; possible values are Horizontal and Vertical

TextBox

SelectedIndex

represents

the

index

selected

within

the

item

selected

within

the

item

selected

within

the

RadioButtonList
SelectedItem

represents

the

RadioButtonList
SelectedItem

represents

the

RadioButtonList
TextAlign

determines

how

the

text

associated

with

the

RadioButtonList is aligned; possible values are Left
and Right

Events
SelectedIndexChanged

raised

when

a

radio

button

within

the

RadioButtonList is selected

TextBox
Properties
AutoPostBack

automatically posts the form containing the TextBox
whenever a change is made to the contents of the
TextBox

Columns

sets the horizontal size of the TextBox in characters

MaxLength

sets the maximum number of characters that may be
entered

Rows

sets the vertical size of the multiline TextBox

Text

specifies the text displayed by the TextBox

TextMode

determines whether the TextBox should render as
SingleLine, Password, or MultiLine

Visible

controls the visibility of the TextBox

Wrap

determines how a multiline TextBox wraps; if set to
True, word wrapping is enabled

627

Appendix A: Web Control Reference

Events
TextChanged

raised when the contents of the TextBox have changed

Xml
Properties
Document

specifies the System
...
XmlDocument object to display

DocumentContent

specifies a string representing the XML document to
display

DocumentSource

specifies the URL of a document to display

Transform

specifies the System
...
Xsl
...
These controls ultimately derive from
the WebControl class, meaning that they, like the web controls themselves, inherit
its properties and methods
...


CompareValidator
Properties
ControlToCompare

628

specifies the ID of the control to use for comparing
values

CustomValidator

ControlToValidate

specifies the ID of the control that you want to validate

Display

shows how the error message within the validation
control will be displayed; possible values are Static,
Dynamic, and None; default is Static

EnableClientScript

enables or disables client-side validation; by default, is
set to Enabled

Enabled

enables or disables client and server-side validation;
default is Enabled

ErrorMessage

specifies the error message that will be displayed to the
user in any associated validation summary control; if
no value is set for the Text property, this message also
appears in the control itself

IsValid

has the value True when the validation check succeeds,
and False otherwise

Operator

specifies the operator to use when performing comparisons; possible values are Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual,
DataTypeCheck

Text

sets the error message displayed by the control when
validation fails

Type

specifies the data type to use when comparing values;
possible values are Currency, Date, Double, Integer,
and String

ValueToCompare

specifies the value used when performing the comparison

Methods
Validate

performs validation and modifies the IsValid property

CustomValidator
ClientValidationFunction

specifies the name of the client-side function to use
for validation

629

Appendix A: Web Control Reference

ControlToValidate

specifies the ID of the control that you want to validate

Display

shows how the error message within the validation
control will be displayed; possible values are Static,
Dynamic, and None; default is Static

EnableClientScript

enables or disables client-side validation; by default, is
set as Enabled

Enabled

enables or disables client and server-side validation; by
default, is set as Enabled

ErrorMessage

specifies the error message that will be displayed to the
user

IsValid

has the value True when the validation check succeeds,
and False otherwise

Text

sets the error message displayed by the control when
validation fails

Methods
Validate

performs validation and modifies the IsValid property

Events
ServerValidate

represents the function for performing server-side validation

RangeValidator
Properties
ControlToValidate
Display

shows how the error message within the validation
control will be displayed; possible values are Static,
Dynamic, and None; default is Static

EnableClientScript

630

specifies the ID of the control that you want to validate

enables or disables client-side validation; set as Enabled
by default

RegularExpressionValidator

Enabled

enables or disables client and server-side validation;
set as Enabled by default

ErrorMessage

specifies the error message that will be displayed to the
user in any associated validation summary control; if
no value is set for the Text property, this message also
appears in the control itself

IsValid

has the value True when the validation check succeeds,
and False otherwise

MaximumValue

sets the maximum value in the range of permissible
values

MinimumValue

sets the minimum value in the range of permissible
values

Text

sets the error message displayed by the control when
validation fails

Type

specifies the data type to use when comparing values;
possible values are Currency, Date, Double, Integer,
and String

Methods
Validate

performs validation and modifies the IsValid property

RegularExpressionValidator
Properties
ControlToValidate

specifies the ID of the control that you want to validate

Display

shows how the error message within the validation
control will be displayed; possible values are Static,
Dynamic, and None; default is Static

EnableClientScript

enables or disables client-side validation; set as Enabled
by default

631

Appendix A: Web Control Reference

Enabled

enables or disables client and server-side validation; by
default, is set as Enabled

ErrorMessage

specifies the error message that will be displayed to the
user

InitialValue

specifies

the

initial

value

specified

by

the

ControlToValidate property
IsValid

has the value True when the validation check succeeds,
and False otherwise

Text

sets the error message displayed by the control

ValidateExpression

specifies the regular expression to use when performing
validation

Methods
Validate

performs validation and modifies the IsValid property

RequiredFieldValidator
Properties
ControlToValidate
Display

shows how the error message within the validation
control will be displayed; possible values are Static,
Dynamic, and None; default is Static

EnableClientScript

enables or disables client-side validation; set as Enabled
by default

Enabled

enables or disables client and server-side validation; by
default, is set as enabled

ErrorMessage

632

specifies the ID of the control that you want to validate

specifies the error message that will be displayed to the
user in any associated validation summary control; if
no value is set for the Text property, this message also
appears in the control itself

ValidationSummary

InitialValue

specifies

the

initial

value

specified

by

the

ControlToValidate property
IsValid

has the value True when the validation check succeeds,
and False otherwise

Text

sets the error message displayed by the control when
validation fails

Methods
Validate

performs validation and modifies the IsValid property

ValidationSummary
Properties
DisplayMode

sets the formatting for the error messages that are displayed within the page; possible values are BulletList,
List, and SingleParagraph; these messages are the
ErrorMessage properties of all validation controls for
which validation has failed

EnableClientScript

enables or disables client-side validation; by default, is
set as Enabled

Enabled

enables or disables client and server-side validation; by
default, is set as Enabled

HeaderText

sets the text that is displayed to the user at the top of
the summary

ShowMessageBox

when the value is set to True, an alert box listing form
fields that caused errors is presented to the user

ShowSummary

enables or disables the summary of error messages

633

Appendix A: Web Control Reference

Navigation Web Controls
SiteMapPath
Properties
CurrentNodeStyle

the style used to display the current node

CurrentNodeTemplate

the template used to display the current node

NodeStyle

the style used to display SiteMapPath nodes

NodeTemplate

the template used to display nodes

ParentLevelsDisplayed

the maximum number of parent nodes to display

PathDirection

specifies the path direction display; possible values are
and

PathDirection
...
RootToCurrent
PathSeparator
PathSeparatorStyle

the styles used to display the path separator

PathSeparatorTemplate

the template used to display the separator

Provider

the SiteMapProvider object associated with the
SiteMapPath; the default site map provider is
XmlSiteMapProvider, which reads its data from the
Web
...
Horizontal or Orientation
...

ExpandDepth

an integer representing the number of TreeView levels that are expanded
when the control is displayed for the first time; default is -1, which displays
all the nodes
ExpandImageToolTip

the tooltip for the image displayed for the “expand” node indicator
ExpandImageUrl

a string representing the URL for a custom image to be used as the “expand”
node indicator
HoverNodeStyle
a TreeNodeStyle object used to define the styles of a node when the cursor

is hovered over it

640

TreeView

ImageSet
a TreeViewImageSet value representing the set of images to be used when
displaying TreeView nodes; default values are Arrows, BulletedList, BulletedList2, BulletedList3, BulletedList4, Contacts, Custom, Events,
Faq, Inbox, News, Simple, Simple2, Msdn, WindowsHelp, and XPFileExplorer

When not using one of these predefined sets, you should define these properties instead: CollapseImageUrl, ExpandImageUrl, LineImagesFolder, and
NoExpandImageUrl
LeafNodeStyle
a TreeNodeStyle representing the style used to render leaf nodes
LevelStyles
a TreeNodeStyleCollection that contains the styles used to render the items
in each TreeView level
LineImagesFolder

a string containing the path to a web-accessible folder that holds the image
files used to connect child nodes to parent nodes; that folder must include
these files: Dash
...
gif, Dashplus
...
gif, L
...
gif, Lplus
...
gif, Noexpand
...
gif, R
...
gif, Rplus
...
gif, Tminus
...
gif
MaxDataBindDepth

defines the maximum number of tree levels to bind to the TreeView control
NodeIndent

an integer representing the number of pixels by which child nodes in the tree
will be indented
Nodes
a TreeNodeCollection containing the root nodes of the tree
NodeStyle
the TreeNodeStyle object that defines the default appearance of all tree

nodes
NodeWrap
a Boolean value indicating whether the text in a node wraps

641

Appendix A: Web Control Reference

NoExpandImageUrl

a string representing the URL for a custom image that indicates nodes that
cannot be expanded
ParentNodeStyle
the TreeNodeStyle object that defines the appearance of parent nodes
PathSeparator

the character used to delimit node values in the ValuePath property
PopulateNodesFromClient

a Boolean value that specifies whether or not node data should be populated
dynamically when necessary, without posting back to the server; default value
is True
RootNodeStyle
a TreeNodeStyle object that defines the appearance of the root node
SelectedNode

a string containing the value of the selected node
SelectedNodeStyle
a TreeNodeStyle object that defines the appearance of the selected node
ShowCheckBoxes
a TreeNodeTypes value that defines which tree nodes should be associated
with text boxes; possible values are All, Leaf, None, Parent, and Root
ShowExpandCollapse

a Boolean value that determines whether or not expansion node indicators
should be displayed
ShowLines

a Boolean value that determines whether or not linking lines between parent
nodes and child nodes should be displayed
SkipLinkText

a string that describes the link that allows screen reader users to skip the
content of this element

642

HTML Server Controls

Target

specifies the target window or frame in which content associated with a menu
item should be displayed when that item is clicked; possible values are _blank,
_parent, _search, _self, and _top

Methods
CollapseAll

collapses all nodes

DataBind

binds the control to its data source

ExpandAll

expands all nodes

FindNode

returns the TreeNode object located at the path specified by the string parameter

Events
SelectedNodeChanged

fires when the currently selected item changes

TreeNodeCheckChanged

fires when a checkbox changes state

TreeNodeCollapsed

fires when a node is collapsed

TreeNodeExpanded

fires when a node is expanded

TreeNodePopulate

fires when a node that has its PopulateOnDemand
property set to True is expanded

HTML Server Controls
When HTML tags are used in an ASP
...
The simple addition of the runat="server" attribute turns
an HTML tag into an HTML control, which we can then access and alter through
our code by means of the identifier given in the control’s id attribute
...
NET’s
HTML controls
...


Properties
Attributes

a collection of the element’s attribute names and their
values

Disabled

if set to True, the control will be disabled

Href

contains the control’s link URL

ID

contains the control’s ID

InnerHtml

contains the content between the element’s opening
and closing tags

InnerText

contains the text between the element’s opening and
closing tags

Name

the name of the anchor

Style

contains the control’s CSS properties

TagName

returns the element’s tag name

Target

contains the target window or frame to be opened

Title

contains the link’s title

Visible

if set to False, the control won’t be visible

Events
ServerClick

raised when the user clicks the link

HtmlButton Control
The HtmlButton control corresponds to the