- •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
Editing DataList Items and Using Templates
C# File: EmployeeDirectory.aspx.cs (excerpt)
// Add content to the Literal control
li.Text = "Employee ID: <strong>" + e.CommandArgument + "</strong><br />";
Disabling View State
If you take a look at the definition of the extraDetailsLiteral control in EmployeeDirectory.aspx, you’ll see that we set its EnableViewState property to False:
File: EmployeeDirectory.aspx (excerpt)
<asp:Literal ID="extraDetailsLiteral" runat="server"
EnableViewState="false" />
When this property is False, its contents aren’t persisted during postback events. In our case, once the visitor clicks another View more details button, all the instances of that Literal control lose their values. This way, at any given moment, no more than one employee’s ID will be displayed. If you change EnableViewState to True (the default value), then click the View more details button, you’ll see that all employee IDs remain in the form, as they’re persisted by the view state mechanism.
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. Our goal here is to allow users to change the name or username of any employee.
Start by adding another button to the ItemTemplate of the DataList. This button will read Edit employee Employee Name and, when clicked, it will cause the item of which it’s a part to become editable.
File: EmployeeDirectory.aspx (excerpt)
<ItemTemplate>
<asp:Literal ID="extraDetailsLiteral" runat="server" EnableViewState="false" />
Name: <strong><%#Eval("Name")%></strong><br /> Username: <strong><%#Eval("Username")%></strong><br /> <asp:LinkButton ID="detailsButton" runat="server"
Text=<%#"View more details about " & Eval("Name")%>
413
Chapter 10: Displaying Content Using Data Lists
CommandName="MoreDetailsPlease" CommandArgument=<%#Eval("EmployeeID")%> /><br />
<asp:LinkButton ID="editButton" runat="server" Text=<%#"Edit employee " + Eval("Name")%> CommandName="EditItem"
CommandArgument=<%#Eval("EmployeeID")%> />
</ItemTemplate>
When an Edit employee button is clicked, we will make the item enter edit mode. 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. All the other items are generated by the ItemTemplate, as usual.
Modify EmployeeDirectory.aspx by adding the EditItemTemplate to the
DataList. 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.
File: EmployeeDirectory.aspx (excerpt)
<EditItemTemplate>
Name: <asp:TextBox ID="nameTextBox" runat="server" Text=<%#Eval("Name")%> /><br />
Username: <asp:TextBox ID="usernameTextBox" runat="server" Text=<%#Eval("Username")%> /><br />
<asp:LinkButton ID="updateButton" runat="server" Text="Update Item" CommandName="UpdateItem" CommandArgument=<%#Eval("EmployeeID")%> />
or
<asp:LinkButton ID="cancelButton" runat="server" Text="Cancel Editing" CommandName="CancelEditing" CommandArgument=<%#Eval("EmployeeID")%> />
</EditItemTemplate>
Finally, before you can see your new template, we need to handle the Edit employee button. Again, when that button is clicked, the DataList’s ItemCommand event is fired. 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. To put a DataList item into edit mode, we set its EditItemIndex to the index of the item, then bind the DataList to its data source again to refresh its contents. Add this code:
Visual Basic |
File: EmployeeDirectory.aspx.vb (excerpt) |
Protected Sub employeesList_ItemCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
414
Editing DataList Items and Using Templates
Handles employeesList.ItemCommand ' Which button was clicked?
If e.CommandName = "MoreDetailsPlease" Then
'Find the Literal control in the DataList item Dim li As Literal
li = e.Item.FindControl("extraDetailsLiteral")
'Add content to the Literal control
li.Text = "Employee ID: <strong>" & e.CommandArgument & _ "</strong><br />"
ElseIf e.CommandName = "EditItem" Then
'Set the index of the item being edited employeesList.EditItemIndex = e.Item.ItemIndex
'Bind again the list to update the list BindList()
End If
End Sub
C# |
File: EmployeeDirectory.aspx.cs (excerpt) |
protected void employeesList_ItemCommand(object source, DataListCommandEventArgs e)
{
// Which button was clicked?
if (e.CommandName == "MoreDetailsPlease")
{
//Find the Literal control in the DataList item Literal li;
li = (Literal)e.Item.FindControl("extraDetailsLiteral");
//Add content to the Literal control
li.Text = "Employee ID: <strong>" + e.CommandArgument + "</strong><br />";
}
else if (e.CommandName == "EditItem")
{
//Set the index of the item being edited employeesList.EditItemIndex = e.Item.ItemIndex;
//Bind again the list to update the list BindList();
}
}
415
Chapter 10: Displaying Content Using Data Lists
Figure 10.5. Editing the DataList
Execute the project now, load the employee directory, and enter one of your items into edit mode, as shown in Figure 10.5.
We need to implement functionality for two more buttons: Update Item, and
Cancel Editing. We’ll take them one at a time, starting with Cancel Editing, which is easier to handle. Modify employeesList_ItemCommand like this:
Visual Basic |
File: EmployeeDirectory.aspx.vb (excerpt) |
|
|
Protected |
Sub employeesList_ItemCommand(ByVal source As Object, _ |
ByVal e |
As System.Web.UI.WebControls.DataListCommandEventArgs) _ |
Handles |
employeesList.ItemCommand |
' Which |
button was clicked? |
If e.CommandName = "MoreDetailsPlease" Then
'Find the Literal control in the DataList item Dim li As Literal
li = e.Item.FindControl("extraDetailsLiteral")
'Add content to the Literal control
li.Text = "Employee ID: <strong>" & e.CommandArgument & _ "</strong><br />"
ElseIf e.CommandName = "EditItem" Then
' Set the index of the item being edited employeesList.EditItemIndex = e.Item.ItemIndex
416
Editing DataList Items and Using Templates
' Bind again the list to update the list BindList()
ElseIf e.CommandName = "CancelEditing" Then
'Cancel edit mode employeesList.EditItemIndex = -1
'Refresh the DataList BindList()
End If
End Sub
C# |
File: EmployeeDirectory.aspx.cs (excerpt) |
protected void employeesList_ItemCommand(object source, DataListCommandEventArgs e)
{
// Which button was clicked?
if (e.CommandName == "MoreDetailsPlease")
{
//Find the Literal control in the DataList item Literal li;
li = (Literal)e.Item.FindControl("extraDetailsLiteral");
//Add content to the Literal control
li.Text = "Employee ID: <strong>" + e.CommandArgument + "</strong><br />";
}
else if (e.CommandName == "EditItem")
{
//Set the index of the item being edited employeesList.EditItemIndex = e.Item.ItemIndex;
//Bind again the list to update the list BindList();
}
else if (e.CommandName == "CancelEditing")
{
//Cancel edit mode employeesList.EditItemIndex = -1;
//Refresh the DataList BindList();
}
}
Execute your project again and check that your new button works. As you can see, exiting edit mode is really simple. You simply need to set the EditItemIndex property of the DataList to -1, then refresh the DataList’s contents.
Let’s deal with the task of updating the record now. 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. The techniques used in this code are the ones we used earlier, but be sure to read the code carefully to ensure that you understand how it works.
Visual Basic |
File: EmployeeDirectory.aspx.vb (excerpt) |
ElseIf e.CommandName = "CancelEditing" Then
'Cancel edit mode employeesList.EditItemIndex = -1
'Refresh the DataList BindList()
ElseIf e.CommandName = "UpdateItem" Then ' Get the employee ID
Dim employeeId As Integer = e.CommandArgument ' Get the new username
Dim nameTextBox As TextBox = _ e.Item.FindControl("nameTextBox")
Dim newName As String = nameTextBox.Text ' Get the new name
Dim usernameTextBox As TextBox = _ e.Item.FindControl("usernameTextBox")
Dim newUsername As String = usernameTextBox.Text ' Update the item
UpdateItem(employeeId, newName, newUsername)
'Cancel edit mode employeesList.EditItemIndex = -1
'Refresh the DataList BindList()
End If
End Sub
C# |
File: EmployeeDirectory.aspx.cs (excerpt) |
else if (e.CommandName == "CancelEditing")
{
//Cancel edit mode employeesList.EditItemIndex = -1;
//Refresh the DataList BindList();
}
else if (e.CommandName == "UpdateItem")
{
// Get the employee ID
int employeeId = Convert.ToInt32(e.CommandArgument); // Get the new username
TextBox nameTextBox = (TextBox)e.Item.FindControl("nameTextBox");
string newName = nameTextBox.Text;
418
Editing DataList Items and Using Templates
//Get the new name TextBox usernameTextBox =
(TextBox)e.Item.FindControl("usernameTextBox"); string newUsername = usernameTextBox.Text;
//Update the item
UpdateItem(employeeId, newName, newUsername);
//Cancel edit mode employeesList.EditItemIndex = -1;
//Refresh the DataList BindList();
}
}
As you can see, a mysterious method named UpdateItem is used to perform the actual update. We’ve created a separate method to make the code easier to manage. Add this code to your code-behind file:
Visual Basic |
File: EmployeeDirectory.aspx.vb (excerpt) |
Protected Sub UpdateItem(ByVal employeeId As String, _ ByVal newName As String, ByVal newUsername As String)
'Declare data objects Dim conn As SqlConnection Dim comm As SqlCommand
'Read the connection string from Web.config Dim connectionString As String = _
ConfigurationManager.ConnectionStrings( _ "Dorknozzle").ConnectionString
'Initialize connection
conn = New SqlConnection(connectionString) ' Create command
comm = New SqlCommand("UpdateEmployee", conn)
'Specify we're calling a stored procedure comm.CommandType = System.Data.CommandType.StoredProcedure
'Add command parameters comm.Parameters.Add("@EmployeeID", Data.SqlDbType.Int) comm.Parameters("@EmployeeID").Value = employeeId
comm.Parameters.Add("@NewName", Data.SqlDbType.NVarChar, 50) comm.Parameters("@NewName").Value = newName comm.Parameters.Add("@NewUsername", Data.SqlDbType.NVarChar, 50) comm.Parameters("@NewUsername").Value = newUsername
'Enclose database code in Try-Catch-Finally
Try
'Open the connection conn.Open()
'Execute the command comm.ExecuteNonQuery()
419
Chapter 10: Displaying Content Using Data Lists
Finally
' Close the connection
conn.Close()
End Try
End Sub
C# |
File: EmployeeDirectory.aspx.cs (excerpt) |
protected void UpdateItem(int employeeId, string newName, string newUsername)
{
//Declare data objects SqlConnection conn; SqlCommand comm;
//Read the connection string from Web.config string connectionString =
ConfigurationManager.ConnectionStrings[
"Dorknozzle"].ConnectionString;
//Initialize connection
conn = new SqlConnection(connectionString); // Create command
comm = new SqlCommand("UpdateEmployee", conn);
//Specify we're calling a stored procedure comm.CommandType = System.Data.CommandType.StoredProcedure;
//Add command parameters comm.Parameters.Add("@EmployeeID", SqlDbType.Int); comm.Parameters["@EmployeeID"].Value = employeeId; comm.Parameters.Add("@NewName", SqlDbType.NVarChar, 50); comm.Parameters["@NewName"].Value = newName;
comm.Parameters.Add("@NewUsername", SqlDbType.NVarChar, 50); comm.Parameters["@NewUsername"].Value = newUsername;
//Enclose database code in Try-Catch-Finally
try
{
//Open the connection conn.Open();
//Execute the command comm.ExecuteNonQuery();
}
finally
{
// Close the connection conn.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. Next, let’s add the UpdateEmployee stored procedure to our database by running the following script using SQL Server Management Studio:
CREATE PROCEDURE UpdateEmployee
(
@EmployeeID Int, @NewName nvarchar(50),
@NewUsername nvarchar(50)
)
AS
UPDATE Employees
SET Name = @NewName, Username = @NewUsername WHERE EmployeeID = @EmployeeID
Finally, execute the project again, load the Employee Directory page, and enter one of the employees into edit mode. You should see a display like the one shown in Figure 10.6.
Figure 10.6. Viewing an employee in edit mode
421