
- •Table of Contents
- •Preface
- •What is ASP.NET?
- •Installing the Required Software
- •Installing the Web Server
- •Installing Internet Information Services (IIS)
- •Installing Cassini
- •Installing the .NET Framework and the SDK
- •Installing the .NET Framework
- •Installing the SDK
- •Configuring the Web Server
- •Configuring IIS
- •Configuring Cassini
- •Where do I Put my Files?
- •Using localhost
- •Virtual Directories
- •Using Cassini
- •Installing SQL Server 2005 Express Edition
- •Installing SQL Server Management Studio Express
- •Installing Visual Web Developer 2005
- •Writing your First ASP.NET Page
- •Getting Help
- •Summary
- •ASP.NET Basics
- •ASP.NET Page Structure
- •Directives
- •Code Declaration Blocks
- •Comments in VB and C# Code
- •Code Render Blocks
- •ASP.NET Server Controls
- •Server-side Comments
- •Literal Text and HTML Tags
- •View State
- •Working with Directives
- •ASP.NET Languages
- •Visual Basic
- •Summary
- •VB and C# Programming Basics
- •Programming Basics
- •Control Events and Subroutines
- •Page Events
- •Variables and Variable Declaration
- •Arrays
- •Functions
- •Operators
- •Breaking Long Lines of Code
- •Conditional Logic
- •Loops
- •Object Oriented Programming Concepts
- •Objects and Classes
- •Properties
- •Methods
- •Classes
- •Constructors
- •Scope
- •Events
- •Understanding Inheritance
- •Objects In .NET
- •Namespaces
- •Using Code-behind Files
- •Summary
- •Constructing ASP.NET Web Pages
- •Web Forms
- •HTML Server Controls
- •Using the HTML Server Controls
- •Web Server Controls
- •Standard Web Server Controls
- •Label
- •Literal
- •TextBox
- •HiddenField
- •Button
- •ImageButton
- •LinkButton
- •HyperLink
- •CheckBox
- •RadioButton
- •Image
- •ImageMap
- •PlaceHolder
- •Panel
- •List Controls
- •DropDownList
- •ListBox
- •RadioButtonList
- •CheckBoxList
- •BulletedList
- •Advanced Controls
- •Calendar
- •AdRotator
- •TreeView
- •SiteMapPath
- •Menu
- •MultiView
- •Wizard
- •FileUpload
- •Web User Controls
- •Creating a Web User Control
- •Using the Web User Control
- •Master Pages
- •Using Cascading Style Sheets (CSS)
- •Types of Styles and Style Sheets
- •Style Properties
- •The CssClass Property
- •Summary
- •Building Web Applications
- •Introducing the Dorknozzle Project
- •Using Visual Web Developer
- •Meeting the Features
- •The Solution Explorer
- •The Web Forms Designer
- •The Code Editor
- •IntelliSense
- •The Toolbox
- •The Properties Window
- •Executing your Project
- •Using Visual Web Developer’s Built-in Web Server
- •Using IIS
- •Using IIS with Visual Web Developer
- •Core Web Application Features
- •Web.config
- •Global.asax
- •Using Application State
- •Working with User Sessions
- •Using the Cache Object
- •Using Cookies
- •Starting the Dorknozzle Project
- •Preparing the Sitemap
- •Using Themes, Skins, and Styles
- •Creating a New Theme Folder
- •Creating a New Style Sheet
- •Styling Web Server Controls
- •Adding a Skin
- •Applying the Theme
- •Building the Master Page
- •Using the Master Page
- •Extending Dorknozzle
- •Debugging and Error Handling
- •Debugging with Visual Web Developer
- •Other Kinds of Errors
- •Custom Errors
- •Handling Exceptions Locally
- •Summary
- •Using the Validation Controls
- •Enforcing Validation on the Server
- •Using Validation Controls
- •RequiredFieldValidator
- •CompareValidator
- •RangeValidator
- •ValidationSummary
- •RegularExpressionValidator
- •Some Useful Regular Expressions
- •CustomValidator
- •Validation Groups
- •Updating Dorknozzle
- •Summary
- •What is a Database?
- •Creating your First Database
- •Creating a New Database Using Visual Web Developer
- •Creating Database Tables
- •Data Types
- •Column Properties
- •Primary Keys
- •Creating the Employees Table
- •Creating the Remaining Tables
- •Executing SQL Scripts
- •Populating the Data Tables
- •Relational Database Design Concepts
- •Foreign Keys
- •Using Database Diagrams
- •Diagrams and Table Relationships
- •One-to-one Relationships
- •One-to-many Relationships
- •Many-to-many Relationships
- •Summary
- •Speaking SQL
- •Reading Data from a Single Table
- •Using the SELECT Statement
- •Selecting Certain Fields
- •Selecting Unique Data with DISTINCT
- •Row Filtering with WHERE
- •Selecting Ranges of Values with BETWEEN
- •Matching Patterns with LIKE
- •Using the IN Operator
- •Sorting Results Using ORDER BY
- •Limiting the Number of Results with TOP
- •Reading Data from Multiple Tables
- •Subqueries
- •Table Joins
- •Expressions and Operators
- •Transact-SQL Functions
- •Arithmetic Functions
- •String Functions
- •Date and Time Functions
- •Working with Groups of Values
- •The COUNT Function
- •Grouping Records Using GROUP BY
- •Filtering Groups Using HAVING
- •The SUM, AVG, MIN, and MAX Functions
- •Updating Existing Data
- •The INSERT Statement
- •The UPDATE Statement
- •The DELETE Statement
- •Stored Procedures
- •Summary
- •Introducing ADO.NET
- •Importing the SqlClient Namespace
- •Defining the Database Connection
- •Preparing the Command
- •Executing the Command
- •Setting up Database Authentication
- •Reading the Data
- •Using Parameters with Queries
- •Bulletproofing Data Access Code
- •Using the Repeater Control
- •More Data Binding
- •Inserting Records
- •Updating Records
- •Deleting Records
- •Using Stored Procedures
- •Summary
- •DataList Basics
- •Handling DataList Events
- •Editing DataList Items and Using Templates
- •DataList and Visual Web Developer
- •Styling the DataList
- •Summary
- •Using the GridView Control
- •Customizing the GridView Columns
- •Styling the GridView with Templates, Skins, and CSS
- •Selecting Grid Records
- •Using the DetailsView Control
- •Styling the DetailsView
- •GridView and DetailsView Events
- •Entering Edit Mode
- •Using Templates
- •Updating DetailsView Records
- •Summary
- •Advanced Data Access
- •Using Data Source Controls
- •Binding the GridView to a SqlDataSource
- •Binding the DetailsView to a SqlDataSource
- •Displaying Lists in DetailsView
- •More on SqlDataSource
- •Working with Data Sets and Data Tables
- •What is a Data Set Made From?
- •Binding DataSets to Controls
- •Implementing Paging
- •Storing Data Sets in View State
- •Implementing Sorting
- •Filtering Data
- •Updating a Database from a Modified DataSet
- •Summary
- •Security and User Authentication
- •Basic Security Guidelines
- •Securing ASP.NET 2.0 Applications
- •Working with Forms Authentication
- •Authenticating Users
- •Working with Hard-coded User Accounts
- •Configuring Forms Authentication
- •Configuring Forms Authorization
- •Storing Users in Web.config
- •Hashing Passwords
- •Logging Users Out
- •ASP.NET 2.0 Memberships and Roles
- •Creating the Membership Data Structures
- •Using your Database to Store Membership Data
- •Using the ASP.NET Web Site Configuration Tool
- •Creating Users and Roles
- •Changing Password Strength Requirements
- •Securing your Web Application
- •Using the ASP.NET Login Controls
- •Authenticating Users
- •Customizing User Display
- •Summary
- •Working with Files and Email
- •Writing and Reading Text Files
- •Setting Up Security
- •Writing Content to a Text File
- •Reading Content from a Text File
- •Accessing Directories and Directory Information
- •Working with Directory and File Paths
- •Uploading Files
- •Sending Email with ASP.NET
- •Configuring the SMTP Server
- •Sending a Test Email
- •Creating the Company Newsletter Page
- •Summary
- •The WebControl Class
- •Properties
- •Methods
- •Standard Web Controls
- •AdRotator
- •Properties
- •Events
- •BulletedList
- •Properties
- •Events
- •Button
- •Properties
- •Events
- •Calendar
- •Properties
- •Events
- •CheckBox
- •Properties
- •Events
- •CheckBoxList
- •Properties
- •Events
- •DropDownList
- •Properties
- •Events
- •FileUpload
- •Properties
- •Methods
- •HiddenField
- •Properties
- •HyperLink
- •Properties
- •Image
- •Properties
- •ImageButton
- •Properties
- •Events
- •ImageMap
- •Properties
- •Events
- •Label
- •Properties
- •LinkButton
- •Properties
- •Events
- •ListBox
- •Properties
- •Events
- •Literal
- •Properties
- •MultiView
- •Properties
- •Methods
- •Events
- •Panel
- •Properties
- •PlaceHolder
- •Properties
- •RadioButton
- •Properties
- •Events
- •RadioButtonList
- •Properties
- •Events
- •TextBox
- •Properties
- •Events
- •Properties
- •Validation Controls
- •CompareValidator
- •Properties
- •Methods
- •CustomValidator
- •Methods
- •Events
- •RangeValidator
- •Properties
- •Methods
- •RegularExpressionValidator
- •Properties
- •Methods
- •RequiredFieldValidator
- •Properties
- •Methods
- •ValidationSummary
- •Properties
- •Navigation Web Controls
- •SiteMapPath
- •Properties
- •Methods
- •Events
- •Menu
- •Properties
- •Methods
- •Events
- •TreeView
- •Properties
- •Methods
- •Events
- •HTML Server Controls
- •HtmlAnchor Control
- •Properties
- •Events
- •HtmlButton Control
- •Properties
- •Events
- •HtmlForm Control
- •Properties
- •HtmlGeneric Control
- •Properties
- •HtmlImage Control
- •Properties
- •HtmlInputButton Control
- •Properties
- •Events
- •HtmlInputCheckBox Control
- •Properties
- •Events
- •HtmlInputFile Control
- •Properties
- •HtmlInputHidden Control
- •Properties
- •HtmlInputImage Control
- •Properties
- •Events
- •HtmlInputRadioButton Control
- •Properties
- •Events
- •HtmlInputText Control
- •Properties
- •Events
- •HtmlSelect Control
- •Properties
- •Events
- •HtmlTable Control
- •Properties
- •HtmlTableCell Control
- •Properties
- •HtmlTableRow Control
- •Properties
- •HtmlTextArea Control
- •Properties
- •Events
- •Index

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. Why not? Well, it wouldn’t make much sense to have one—GridView knows what to do when an editing action is approved to take place. More specifically, when a row enters edit mode, it is displayed using the default editing style of the column. The built-in column types (such as bound columns, check box columns, and so on) have built-in editing templates, which you can customize by providing custom templates.
Entering Edit Mode
To get a better grasp on all this theory, let’s look at another example. Here, we’ll modify the DetailsView control to let users update employee data. To implement
GridView or DetailsView editing, we can use a CommandField column.
Let’s get started. Open AddressBook.aspx in the designer, click the DetailsView’s smart tag, and choose Add New Column…. In the Choose a field type drop-down, select CommandField, and check the Edit/Update checkbox, as shown in Figure 11.14.
Figure 11.14. Adding the Edit/Update CommandField
If you’d prefer to add the new column by hand, do so by adding it in AddressBook.aspx. Either way, you should end up with the following code:
456

Entering Edit Mode
File: AddressBook.aspx (excerpt)
<asp:DetailsView id="employeeDetails" runat="server" AutoGenerateRows="False">
<Fields>
<asp:BoundField DataField="Address" HeaderText="Address" /> <asp:BoundField DataField="City" HeaderText="City" /> <asp:BoundField DataField="State" HeaderText="State" /> <asp:BoundField DataField="Zip" HeaderText="Zip" /> <asp:BoundField DataField="HomePhone"
HeaderText="Home Phone" /> <asp:BoundField DataField="Extension"
HeaderText="Extension" />
<asp:CommandField ShowEditButton="True" />
</Fields>
<HeaderTemplate>
<%#Eval("Name")%>
</HeaderTemplate>
</asp:DetailsView>
The new item will appear in the designer as an Edit link immediately below the list of columns. 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. The DetailsView control doesn’t know how to switch itself to edit mode, but fortunately, it’s extremely easy to write the code yourself.
To have Visual Web Developer generate the ModeChanging event signature for you, open AddressBook.aspx in Design View, select the DetailsView control, click the yellow button with the lightning symbol in the Properties window to bring up the list of the control’s events, and double-click on the ModeChanging entry. This will generate an empty event handler for you, and take you straight to the function in the code-behind file. Complete the generated code like this:
Visual Basic |
File: AddressBook.aspx.vb (excerpt) |
|
|
Protected |
Sub employeeDetails_ModeChanging( _ |
ByVal sender As Object, _ |
|
ByVal e |
As System.Web.UI.WebControls.DetailsViewModeEventArgs) _ |
Handles |
employeeDetails.ModeChanging |
'Change current mode to the selected one employeeDetails.ChangeMode(e.NewMode)
'Rebind the grid
BindDetails()
End Sub
457

Chapter 11: Managing Content Using Grid View and Details View
C# |
File: AddressBook.aspx.cs (excerpt) |
protected void employeeDetails_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
//Change current mode to the selected one employeeDetails.ChangeMode(e.NewMode);
//Rebind the grid
BindDetails();
}
Execute the project and click the Edit button. This will transform the control as shown in Figure 11.15.
Figure 11.15. The DetailsView in edit mode
In order to understand the code in employeeDetails_ModeChanging, you need to know about the display modes of the DetailsView control. The DetailsView
458

Using Templates
control supports three display modes. You can change the current mode using its ChangeMode method, providing as parameter one of these values:
DetailsViewMode.ReadOnly
This is the default mode, which is used to display data. When you execute your project, and load the details of an employee, you see those details in
ReadOnly mode.
DetailsViewMode.Edit
This mode is used to edit an existing record. We saw this mode in action earlier, when we clicked the Edit button.
DetailsViewMode.Insert
We use this mode to insert a new record. It’s similar to the edit mode, except all the controls are empty, so you can fill in data for a new item.
If you look at the employeeDetails_ModeChanging, you’ll see it receives a parameter named e that is an object of class DetailsViewModeEventArgs. e’s NewMode property tells us which display mode was requested by the user. Its value will be DetailsViewMode.Edit when the ModeChanging event is fired as a result of the
Edit button being clicked. 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. With this code, you’ve implemented the functionality to make both the Edit and Cancell buttons work correctly, as we’ll see in an example shortly.
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. We’ll create the event handler later; next, we want to improve our existing solution using templates.
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. In the smart tag menu of the GridView and DetailsView controls, an option called Edit Columns (for the GridView) or Edit Fields (for the DetailsView) is available. Selecting that option opens a dialog that provides us with a great deal of control over the options for each column or field.
459

Chapter 11: Managing Content Using Grid View and Details View
You’ll notice a Convert this field into a TemplateField link in the dialog. Let’s see how this works. Click the smart tag of your DetailsView control, then click Edit Fields. In the dialog that appears, select the Address field from the Selected fields list, as shown in Figure 11.16.
Figure 11.16. 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.
So, what happened? Let’s switch AddressBook.aspx to Source View. After you convert the field to a template field, its definition will look like this:
File: AddressBook.aspx (excerpt)
<asp:DetailsView id="employeeDetails" runat="server" AutoGenerateRows="False">
<Fields>
<asp:TemplateField HeaderText="Address"> <EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
460

Using Templates
Text='<%# Bind("Address") %>'></asp:TextBox> </InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="City" HeaderText="City" />
<asp:CommandField ShowEditButton="True" /> </Fields>
<HeaderTemplate>
<%#Eval("Name")%>
</HeaderTemplate>
</asp:DetailsView>
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. Despite these alterations, the current functionality hasn’t changed: you can still execute your project and load the address book, and it will continue to work as before. 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. The power is in your hands. For example, you can widen the TextBox controls used to edit your fields, as well as performing other kinds of customizations. You can also give specific IDs to the inner template controls, rather than using their default generic names, so you can find them easily when you need to.
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. Thus, when the grid enters edit mode, that particular column won’t be transformed into a TextBox, so its read-only behavior will be conserved.
Now, convert the other fields—except for CommandField—to template fields. Then, we’ll modify the generated code by altering the TextBox controls, and assigning appropriate names to our controls. 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.1
File: AddressBook.aspx (excerpt)
<asp:TemplateField HeaderText="Address"> <EditItemTemplate>
<asp:TextBox ID="editAddressTextBox" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertAddressTextBox" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="addressLabel" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField> <asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="editCityTextBox" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="insertCityTextBox" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="cityLabel" runat="server" Text='<%# Bind("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
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. Adding more fields is a trivial task, and the code that’s needed to update all the fields is included in the code archive.
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.17.
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.
462