
Beginning ASP.NET 2.0 With CSharp (2006) [eng]
.pdf
Chapter 6
5.Save the file and from the right mouse menu select View in Browser.
6.Make sure your system date is set between August 20 and May 31.
7.Select a player and try to delete him. You’ll see a message telling you that players cannot be deleted during the season, and the player is not deleted.
8.Change the system clock so that the date is out of season — that is, between June 1 and August 19.
9.Select a player and try to delete him. You may want to add a new test player just so that you can delete him, to save you deleting real squad members.
How It Works
This example relies on the fact that the Deleting event is raised before the actual action takes place, which gives you the opportunity to cancel the event. One of the keys to how this works are the parameters of the event procedure, the declaration of which is shown here:
protected void DetailsDataSource_Deleting(object sender, System.Web.UI.WebControls.SqlDataSourceCommandEventArgs e)
You can see that the second parameter provides extra information, but not only that it allows you to send information back to ASP.NET. One of the properties of the parameter e is called Cancel, and if you set this to true, the event will be cancelled and the action (the deletion) will not take place. Take a look at the code used to determine whether or not the player should be deleted.
You start with some declarations, which will be used to store date information:
DateTime today = DateTime.Now; int startYear;
int endYear; DateTime seasonStart; DateTime seasonEnd;
The first line sets the variable today to the current date. The variables startYear and endYear indicate the year in which the season starts and ends, and seasonStart and seasonEnd are the actual dates for the start and end of the season.
To determine the start and end year you see if the current date is after May. If it is, you know that the season has ended, or is already under way, so the start year is the current year and the end year is next year. If the current date is before May, you are in the second half of the season, so the start year was last year and the end year is the current year:
if (today.Month > 5)
{
startYear = today.Year; endYear = today.Year + 1;
}
198

Events and Code
else
{
startYear = today.Year - 1; endYear = today.Year;
}
Next you create the actual start and end dates of the season, using the start and end year already set:
seasonStart |
= new DateTime(startYear, 8, 20); |
// |
20th |
August |
seasonEnd = |
new DateTime(endYear, 5, 31); |
// |
31st |
May |
Now you check to see if the current date falls within the season start and end dates. If it does, you set the Cancel property of the parameter e to true, so when the event procedure ends the event action (the delete) will be cancelled. You also display a message to tell the user that players cannot be deleted during the season:
if (today >= seasonStart && today <= seasonEnd)
{
e.Cancel = true;
Message.Text = “Cannot delete players during the season”;
}
If you are outside of the season, players can be deleted, so you simply clear any message and rebind the grid (so that the deleted player doesn’t still show in the grid). Because you haven’t set the Cancel property of parameter e to true (it is false by default), the action will take place, and the player will be deleted:
{
GridView1.DataBind(); Message.Text = “”;
}
So what you’ve seen here is that some events can be cancelled, which allows you to build logic into your applications, enabling you to control the actions that are run. This also means that events that you think will run might not. For example, it was mentioned earlier that some of these events are paired. So, as well as the Deleting event, there is a Deleted event, and if you cancel the Deleting event the Deleted event isn’t run. The logic of this is shown in Figure 6-21.
This process is also the same for inserted and updated items, where the Inserting and Updating event procedures are used. In all three cases you can set the Cancel property of the parameter to true to cancel the event.
199

Chapter 6
FirstName Chris
LastName Christopher
Position Left Back
PictureURL aaronson.jpg
Date Joined
Date Left
Edit Delete New
SqlDataSource - DetailsDataSource
Deleting |
Deleted |
Event raised
Is deletion |
Yes |
|
|
Allowed? |
|
No |
|
Event |
Event |
Cancelled |
Runs |
Figure 6-21
Global Events
So far in this chapter you’ve seen that events are raised by controls or by pages, but there is a third type of event — an application event. Application events are raised by ASP.NET in response to certain conditions, and these are stored in the Global Application Class, global.asax, a code-only file.
The global.asax page has several events:
Application_Start, which is raised when the application first starts. This is when the first user accesses the site and should be used to set any initial start conditions.
200

Events and Code
Application_End, which is raised when the application stops.
Session_Start, which is raised when a user starts a session. This is when the user starts accessing the site for the first time, and includes the time when a user closes the browser window and opens it again.
Session_End, which is raised when a user session ends. This isn’t when the browser window is closed, because sessions have a timeout — if there is no user activity within that time, the session ends.
Application_Error, which is raised when an unhandled error occurs.
Profile_OnMigrateAnonymous, which is raised when an anonymous user logs in, and allows migration of any Profile properties.
You can create a Global Application Class in the same way as adding normal Web Forms, and when created, the first four events in the preceding list will be created for you. They’ll have no code, but will be ready for you to add code if you need it.
In the Wrox United application, none of the first four events are used, but the latter two are. The Application_Error event is covered in Chapter 15, which looks at error handling, and the Profile_OnMigrateAnonymous event is covered in Chapter 11, which looks at the Profile.
Summar y
This chapter covered a lot about events, and you’ve seen that they can be raised under a number of different circumstances. First you looked at the ASP.NET page itself, where an event is raised when the page is loaded, which allows you to take some action before anything is shown to the user. Additionally, this chapter examined the following topics:
The ASP.NET page has the IsPostback property that allows you to identify whether this is the first time the page has been displayed, or whether the user has clicked a button.
Button controls, where an event is raised when the user clicks the button. You saw that similar types of controls (the Button and ImageButton controls) have similar events (the Click event).
Events that are raised by ASP.NET itself, both directly (such as the binding of data from a database) and indirectly (such as updating database records). These events give you an opportunity to interact with the process of displaying or updating data, and allow you to fine tune the interface and provide user feedback.
How some events can be cancelled, thus canceling any action they trigger, such as another event. In the example you saw that you can stop the deletion of data by using an event procedure.
Now that you’ve had a look at events, and especially some related to data, it’s time to look at databases in more depth. The next chapter looks at some of the data controls and shows you how data can be fetched from the database and displayed for easy use by the user.
201

Chapter 6
Exercises
1.In the Chapter06 project create a new Web Form called Lists.aspx and add a ListBox control to the page, and add three list items with values of One, Two, and Three. Add a Label control and a Button control to the page. In the Click event of the Button, display the selected value of the
ListBox in the Label.
2.Modify Exercise 1 so that just selecting an item in the list posts back to the server (meaning you don’t need to click the button). You’ll need to add an event procedure to the ListBox, and in that event procedure you can use the same code from the Click event of the Button to display the selected value in the Label. Hint: The terms postback and automatic might be useful in your hunt for correct properties.
3.Modify the EditSquad.aspx example so that the GridView is refreshed when a new player is added to the squad. The technique is similar to the code you already have, but you’ll need to use a different event. Remember that you can use the drop-down lists in the code view to find the events.
202

7
Reading Data
The hallmark of dynamic web application pages is the capability to use information from a database. No other capability so widely expands the horizons of functionality for the visitor. The majority of information in an enterprise is held in databases, so it is imperative that a web application representing a business interact with that data. A tremendous effort by the ASP.NET 2.0 development team has reduced the knowledge and lines of code needed to work with data. This chapter and Chapter 8 explain how to implement the data-based features.
This chapter covers several major ideas:
The theory of using data in ASP.NET 2.0, including a brief overview of the theory and terminology of databases, an introduction to ASP.NET 2.0 data source controls and databound controls, and the role of VWD in creating data-based pages
Data source controls
Data-bound selection lists
Various data-bound controls, including GridView, DataList, Repeater, DetailsView, and FormView
Data source controls with parameters
Implementing multiple data controls that work together
Working with XML data
By the end of the chapter, you will have the tools and experience to use ASP.NET 2.0 server-side controls to present on your pages information that comes from a database.
Introducing Databases
Before starting on the ASP.NET 2.0 data controls, take a moment to consider sources of data. Data can be broadly divided into one of three categories. Relational data is organized into sets of tables according to rules of normalization. This category includes the data held in Microsoft Access,

Chapter 7
Microsoft SQL Server, Oracle, SAP, DB2, and MySQL. A second category of data resides in tree structures, such as XML files, the Windows registry, and the Windows file system. Last, data can be held in a wide range of miscellaneous types, such as Excel files, text files, or proprietary formats. This book (as per the vast majority of web site data interaction) discusses relational data and XML files.
Relational databases divide information into tables, and the tables contain records (also called rows). A record represents one instance of the topic of the table. A table contains multiple fields, or columns, that organize values by their type. For example, a table of employees could contain a record for each employee. The table’s columns may be NameFirst, NameLast, DateOfHire, and so forth. For each column there would be a value for each record. A group of tables makes a database in most management systems. In Microsoft SQL Server, which is used in this book, one or more databases together make an instance of the server. Typically, tables contain only the data. The description of how the data is organized, the names of fields, and restrictions all reside in a separate structure of the database called metadata.
XML files are different from relational databases. First, instead of tables, the data is organized into a tree with branches of the tree holding finer and finer points of data. Each set of data and each individual datum are contained in a node. For example, an Employees XML file would have an Employees node that would represent the main trunk. Then there would be a limb for each employee. From that limb would be branches for FirstName, LastName, and so on. Second, an XML file is self-describing in that the metadata is included with the data. Each piece of information has an HTML tag that acts like a container that states the description of that data. For example, a datum like “John” would actually be stored as <NameFirst>John</NameFirst>. Although the self-descriptors can make an XML file huge, they make it easy to understand the data without having the metadata information.
Almost all sources of data have a system that controls who is allowed to use the data. The first step in security is authentication, wherein the system determines who is asking to use it. The topic of authentication was covered in detail in Chapter 4, so we won’t spend much time on it here. Basically, there are two types of authentication: Windows Authentication (also known as Trusted Security) and SQL Authentication. The decision of which authentication to use is made when the database is installed. With SQL Server Express, you have the option of Windows Authentication or Mixed. Mixed means you can use either Windows Authentication or SQL Authentication. SQL Server Express installs, by default, with Mixed Authentication. This book uses Windows Authentication.
This book mainly uses Microsoft’s SQL Server. The product is sold with different sets of features, but for our use the simplest version (SQL Server Express) is adequate. Fortunately, Microsoft provides SQL Server Express free of charge, and automatically installs with the instructions given in this book for the setup. The beauty of SQL Server Express is that when you deploy your site to the public, all of your code fits without modification into the full-featured SQL Server.
After you are authenticated (you prove that you actually are who you say you are), there will probably be a set of rights and limitations for your use of the data. First are restrictions in how you can look at data. Database administrators (DBAs) generally restrict direct access to tables. Instead, data may only be available to you through a view or query that contains limited fields or records. Second, you may have limits on how (or if) you can change data. Last, even if you have the right to change data, there may be restrictions (called constraints) on how data can be changed. To use Wrox United as an example, you generally cannot delete a team that is listed in the schedule (thus leaving the schedule with the logical fault of a game without an existing team).
204

Reading Data
Using ASP.NET 2.0’s Data Controls
Chapter 3 presented the idea that ASP.NET offers server-side controls. These controls contain code written by Microsoft that offers various behaviors, such as a drop-down list or a button. ASP.NET 2.0 has two sets of controls that are specific to working with data. The first set is data source controls that enable a page to connect to a source of data and to read from and write to that source. However, a data source control has no means to display data on an ASP.NET 2.0 page, which is where data-bound controls come into play. Data-bound controls display data to the user by rendering data onto a page. This chapter discusses data source controls and the reading behaviors of data-bound controls.
Almost all data source controls can work with almost all data-bound controls. This gives designers a mix-and-match solution. Pick the data source control that is optimized for the data and then pick a databound control that displays the information as desired.
Introducing Data Source Controls
ASP.NET 2.0 ships with several types of data source controls that are tailored to work with different types of data sources. These controls are as follows:
The SqlDataSource control allows connections to most relational databases. The Sql in its name refers to databases that understand the SQL language. That includes almost every kind of database that holds its data in a relational format. Note that the Sql does not refer only to the Microsoft SQL Server database management system. SqlDataSource controls utilize one of several providers that are specific to different kinds of databases. The default provider is for Microsoft SQL Server. Another provider is for Oracle. Both of these are written in managed code, the most robust option in the .NET Framework. ASP.NET 2.0 contains an additional provider that can communicate with any database that is OLEDB-enabled (OLEDB is an acronym for Object Linking and Embedding for Databases). Because OLEDB is an old standard, it comprises almost every other database management system including IBM DB2, MySQL, and SAP. However, the provider for OLEDB connections is not written in managed code. That means it does not meet all the requirements of being .NET technology, but it still can work with
.NET. We can expect third parties to publish more data source controls and providers and can hope that they are in proper managed code.
If you begin writing more advanced scenarios, you will discover that OLEDB data source controls are not part of the System.Data hierarchy. These controls actually reside in the System.Web.UI.Controls namespace. But this point does not arise for most scenarios where you can just drag data controls from the toolbar.
The AccessDataSource control is a special case of the SqlDataSource control that contains a provider optimized for Microsoft Access.
The XMLDataSource control allows connection to XML sources.
205

Chapter 7
The SiteMapDataSource control, a specialized form of the XMLDataSource control, is optimized for the specific architecture of the ASP.NET 2.0 web application site map (as you built in Chapter 2).
The ObjectDataSource control connects to business objects you build yourself (discussed in Chapter 10).
Regardless of which data source control (and in the case of the SqlDataSource, which provider) you use, the data source control will enable a set of behaviors for your ASP.NET 2.0 page. These include a connection to the database and enablement of behaviors such as reading and writing data, which are available to data-bound controls that display data and receive input from the user.
If you are familiar with older versions of ASP, the ASP.NET 2.0 data source controls instantiate ADO.NET objects. Therefore, ADO.NET provides the underlying technology for data access. The creation and manipulation of ADO.NET objects for most scenarios is now handled automatically (and correctly and efficiently) by the higherlevel data source control objects.
In summary, the data source controls create the background infrastructure needed to use data. However, they do not create any rendering on the web page (see the next section for those capabilities). Rather, they make the data behaviors like reading and writing to data stores available to data-bound controls.
Introducing Data-Bound Controls
Data-bound controls provide the link between the data source controls and the user. They take the data and behaviors of the data source control and render it to the visitor. This division of labor works very well. You can select any data source control and link that to any of the data-bound controls. With just a few exceptions, it is a mix-and-match scenario.
Data-bound controls encapsulate remarkable amounts of behavior. For example, the GridView control can not only display data in a table, but it offers sorting, selecting, paging through subsets, and one-click transition to data editing. If your needs extend beyond these capabilities, you can write custom code hooked into events exposed by the GridView control.
There is one constraint on the compatibility of data source controls and data-bound controls. Each control is optimized for tabular data, tree data, or custom class data. For example, XML data is organized as a tree and thus best accessed with the XMLDataSource control and displayed in Menu or SiteMapPath data-bound controls. SQL Server data is organized into tables and thus accessed with the SqlDataSource control and displayed in GridView (tables) or DetailsView. List-type data-bound controls can display either source of data. You can twist the controls to cross-utilize types of data, but in general it is best to stick to their intended purpose.
Four general groups of data-bound controls ship with ASP.NET 2.0. Because there is overlap in their functionality, this chapter spends some time differentiating them. First you will look at their renderings, then a comparison chart, and finally a guide to selecting the correct data-bound control for your purposes.
206

Reading Data
Note that other controls, such as text boxes, can be data-bound. However, these independent controls are best connected to data in the context of a template within one of the controls just mentioned. This topic is discussed in detail in Beginning ASP.NET 2.0 Databases from Wrox, ISBN 0-4717-8134-7.
The trick with data-bound controls arises in the selection. It can be confusing in the first attempts to get the correct control for your purpose. To help, the following sections organize the data-bound controls into four groups. Later in the chapter, you will practice using each of them in a series of exercises.
Tabular Controls
Tabular controls produce the classic HTML table listing the data of records, albeit with opportunity for significant enhancements. These controls show multiple records in rows and one or more fields from each record as columns. The GridView control shows one value (datum) in each cell in a table layout. The DataList and Repeater controls behave in the same way, and render each cell with all of the fields for one record. Figure 7-1 shows how these controls look in a browser.
Figure 7-1
The GridView control offers the most behaviors, as it can read, edit, and select records. The DataList control allows reading and editing, whereas the Repeater is a read-only control. The name of DataList is a bit confusing because you have a separate set of List controls that are optimized for selecting a record. The DataList is a display control in a tabular format.
Single Record Display Controls
Single record controls (DetailsView and FormView) display one record at a time. You can think of them as a deck of playing cards in a pile face up. At any moment all of the cards are there, but you can only see the top one. You have to navigate down through the deck to see other cards (see Figure 7-2 for an example of the DetailsView control). Single record controls have navigation features to permit the visitor to go to the next record, jump to a specific record, or fly to the first or last record. The DetailsView control provides some default layout when you create the control, whereas the FormView control creates a blank slate upon which you create the entire layout. Both of these data-bound controls support the reading, editing, and creation of new records.
207