- •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
More Data Binding
The rest of the code comprises the typical data access routine, involving a
SqlConnection object, a SqlCommand object, and a SqlDataReader object. 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. If you save and run this page, it should appear as shown in Figure 9.9.
More Data Binding
The term “data binding” describes the act of associating a data source with a data consumer. In our previous examples, the data source was an SqlDataReader object, and the consumer was a Repeater control that read and displayed the data. Data binding typically involves setting the DataSource property of the consumer object to the data source object, and calling the DataBind method to apply the binding:
Visual Basic
' Bind the reader to the repeater employeesRepeater.DataSource = reader employeesRepeater.DataBind()
C#
// Bind the reader to the repeater employeesRepeater.DataSource = reader; employeesRepeater.DataBind();
As mentioned earlier, ASP.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. To explore the process of control binding further, let’s open the Help Desk page again. If you remember, we left the Category and Subject drop-down lists empty back in Chapter 5. We did so because we knew that, eventually, those items would have to be populated dynamically through code. 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. In order to make the necessary changes to the controls, we would have to open every page that contained lists of categories and subjects.
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. Whenever a change needs to be made, we can make it once within the database; all the controls that are bound to that database table will change automatically.
365
Chapter 9: ADO.NET
Let’s go ahead and add the necessary code to Page_Load in HelpDesk.aspx to populate the DropDownList controls from the database. After the changes are made, the lists will be populated with the data you added to your database in Chapter 7, as illustrated in Figure 9.10.
Figure 9.10. A drop-down list created with data binding
Open HelpDesk.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. Then, add the following code:
Visual Basic |
File: HelpDesk.aspx.vb (excerpt) |
Imports System.Data.SqlClient
Imports System.Configuration
Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.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.config
366
More Data Binding
Dim connectionString As String = _ ConfigurationManager.ConnectionStrings( _ "Dorknozzle").ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
'Create command to read the help desk categories categoryComm = New SqlCommand( _
"SELECT CategoryID, Category FROM HelpDeskCategories", _ conn)
'Create command to read the help desk subjects
subjectComm = New SqlCommand( _
"SELECT SubjectID, Subject FROM HelpDeskSubjects", conn) ' Enclose database code in Try-Catch-Finally
Try
'Open the connection conn.Open()
'Execute the category command reader = categoryComm.ExecuteReader()
'Populate the list of categories categoryList.DataSource = reader categoryList.DataValueField = "CategoryID" categoryList.DataTextField = "Category" categoryList.DataBind()
'Close the reader
reader.Close()
'Execute the subjects command reader = subjectComm.ExecuteReader()
'Populate the list of subjects subjectList.DataSource = reader subjectList.DataValueField = "SubjectID" subjectList.DataTextField = "Subject" subjectList.DataBind()
'Close the reader
reader.Close() Finally
' Close the connection conn.Close()
End Try End If
End Sub
C# |
File: HelpDesk.aspx.cs (excerpt) |
using System.Data.SqlClient;
protected void Page_Load(object sender, EventArgs e)
{
367
Chapter 9: ADO.NET
if (!IsPostBack)
{
//Declare objects SqlConnection conn; SqlCommand categoryComm; SqlCommand subjectComm; SqlDataReader reader;
//Read the connection string from Web.config string connectionString =
ConfigurationManager.ConnectionStrings[
"Dorknozzle"].ConnectionString;
//Initialize connection
conn = new SqlConnection(connectionString);
//Create command to read the help desk categories categoryComm = new SqlCommand(
"SELECT CategoryID, Category FROM HelpDeskCategories", conn);
//Create command to read the help desk subjects subjectComm = new SqlCommand(
"SELECT SubjectID, Subject FROM HelpDeskSubjects", conn);
try
{
//Open the connection
conn.Open();
//Execute the category command reader = categoryComm.ExecuteReader();
//Populate the list of categories categoryList.DataSource = reader; categoryList.DataValueField = "CategoryID"; categoryList.DataTextField = "Category"; categoryList.DataBind();
//Close the reader
reader.Close();
//Execute the subject command reader = subjectComm.ExecuteReader();
//Populate the list of categories subjectList.DataSource = reader; subjectList.DataValueField = "SubjectID"; subjectList.DataTextField = "Subject"; subjectList.DataBind();
//Close the reader
reader.Close();
}
finally
{
// Close the connection
368
More Data Binding
conn.Close();
}
}
}
You’ll notice that the guts of Page_Load are enclosed in an If statement, which tests to see if IsPostBack is True. But just what is this IsPostBack?
Earlier, in Chapter 2, we explored the View State mechanism that ASP.NET uses to remember the data in its controls. View State allows your user controls to remember their states across page loads. Every time an event that needs to be handled on the server is raised, the form in the page is submitted to the server—a process known as a post back. 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.
After such an event occurs, all the controls in the web form retain their values, but the Page_Load method is executed again regardless. In consequence, if you click the Submit Request button ten times, Page_Load will be executed ten times. If the data access code that fills the form with values is in Page_Load, the database will be queried ten times, even though the data that needs to be displayed on the page doesn’t change!
It’s here that IsPostBack comes into play. 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.
Referring to IsPostBack
IsPostBack is actually a property of the Page class, but since our web form is a class that inherits from Page, we can refer to IsPostBack directly. If we wanted to, we could refer to this property as Me.IsPostBack in VB, or this.IsPostBack in C#.
Using the IsPostBack Property Appropriately
It’s not always appropriate to use IsPostBack as we’re using it here. 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. In cases in which the data in the drop-down lists may change, it may be appropriate to access the database and re-fill the form with data every time the form is loaded. 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.NET
their selection triggers a request to the server to load a list of all models of car made by that manufacturer.
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. We retrieve the connection string from Web.config, create a new connection to the database, and set up our SqlCommand objects. In this page, we retrieve two lists—a list of help desk request categories and a list of subjects—so we’ll need to execute two queries. These queries are stored in two SqlCommand objects: categoryComm and subjectComm.
Next, inside a Try-Catch-Finally block, we execute the commands and bind the data in our SqlDataReader to the existing controls. First, we execute categoryComm to retrieve a list of categories; then, we bind that list to categoryList:
Visual Basic |
File: HelpDesk.aspx.vb (excerpt) |
|
|
' Execute the category command |
|
reader = categoryComm.ExecuteReader() |
|
'Populate the list of categories categoryList.DataSource = reader categoryList.DataValueField = "CategoryID" categoryList.DataTextField = "Category" categoryList.DataBind()
'Close the reader
reader.Close()
C# |
File: HelpDesk.aspx.cs (excerpt) |
//Execute the category command reader = categoryComm.ExecuteReader();
//Populate the list of categories categoryList.DataSource = reader; categoryList.DataValueField = "CategoryID"; categoryList.DataTextField = "Category"; categoryList.DataBind();
//Close the reader
reader.Close();
Note that not all controls handle their bindings in the same way. In this case, we want the DropDownList control to display the data from the Category column of the HelpDeskCategories table. The DropDownList control is cleverly designed, and it can also store an ID associated with each item in the list. This can be very helpful when we’re performing database operations using the items selected from
370