BUY THIS BOOK
Add to Cart

Print Book $54.95


Add to Cart

Print+PDF $71.44

Add to Cart

PDF $43.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £38.99

What is this?

Looking to Reprint or License this content?


ASP.NET 2.0 Cookbook
ASP.NET 2.0 Cookbook, Second Edition

By Michael A. Kittel, Geoffrey T. LeBlond
Book Price: $54.95 USD
£38.99 GBP
PDF Price: $43.99

Cover | Table of Contents


Table of Contents

Chapter 1: Master Pages
Most applications use a common HTML design for the majority of their pages, and in the past, developers have conceived many techniques to reduce the replication of the identical HTML in the application pages. However, none of those techniques met the primary goals of providing the HTML in one place or made it easy for non-technical personnel to edit the HTML.
ASP.NET 2.0 provides a new approach with master pages that comes close to meeting these primary goals. Master pages contain all of the common HTML, server controls, and code that would normally be replicated in some fashion in the application pages. You place one or more content placeholders in the master to reserve the space for page-specific content. Content pages provide the content specific to the page and need only reference the desired master page. When a user requests a content page, ASP.NET merges the output of the master page with the output of the content page, resulting in a page that combines the master page layout with the output of the content page.
This chapter provides four recipes for master pages. These include a quick master/content recipe to familiarize you with the technique. Next, we show how to extend a master page's content to include content for other application pages, which you might want to do, for example, when you want your login page to have one appearance and the pages that follow it to build on that appearance. The third recipe describes how to set the master page for pages within a folder structure without having to set the master page for each content page explicitly. This is handy when you want to use the same master page for the majority of your content pages but change to another master page as needed without having to edit all of the pages in the application. The last recipe describes how to set the master page programmatically, which provides the ability to change how the application appears at runtime; this approach is useful when you want to change the appearance of the rendered pages based on the season or client branding of some sort.
In addition to showing you some useful techniques for using master pages, the recipes found in this chapter serve to provide the consistent appearance for all the recipes in the book. In particular, you will see that we use Recipe 1.1's
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Most applications use a common HTML design for the majority of their pages, and in the past, developers have conceived many techniques to reduce the replication of the identical HTML in the application pages. However, none of those techniques met the primary goals of providing the HTML in one place or made it easy for non-technical personnel to edit the HTML.
ASP.NET 2.0 provides a new approach with master pages that comes close to meeting these primary goals. Master pages contain all of the common HTML, server controls, and code that would normally be replicated in some fashion in the application pages. You place one or more content placeholders in the master to reserve the space for page-specific content. Content pages provide the content specific to the page and need only reference the desired master page. When a user requests a content page, ASP.NET merges the output of the master page with the output of the content page, resulting in a page that combines the master page layout with the output of the content page.
This chapter provides four recipes for master pages. These include a quick master/content recipe to familiarize you with the technique. Next, we show how to extend a master page's content to include content for other application pages, which you might want to do, for example, when you want your login page to have one appearance and the pages that follow it to build on that appearance. The third recipe describes how to set the master page for pages within a folder structure without having to set the master page for each content page explicitly. This is handy when you want to use the same master page for the majority of your content pages but change to another master page as needed without having to edit all of the pages in the application. The last recipe describes how to set the master page programmatically, which provides the ability to change how the application appears at runtime; this approach is useful when you want to change the appearance of the rendered pages based on the season or client branding of some sort.
In addition to showing you some useful techniques for using master pages, the recipes found in this chapter serve to provide the consistent appearance for all the recipes in the book. In particular, you will see that we use Recipe 1.1's
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating a Quick Master/Content Page Arrangement
You want to generate a master/content page arrangement quickly to explore the approach used for master pages.
Create a .master file that contains the common HTML for your pages and then create an .aspx file that contains the page-specific content.
Create a new master page by following these steps:
  1. Select your web site in the Solution Explorer.
  2. Right-click and select Add New Item from the context menu.
  3. Select Master Page from the Add New Item dialog.
In the .master file of the master page:
  1. Add the HTML that is common for your application pages.
  2. Add an asp:ContentPlaceHolder control for each portion of the page that will have page-specific content.
  3. Set the ID attribute to a unique identifier.
In the .aspx file:
  1. Set the MasterPageFile attribute of the @Page directive to the name of the .master file.
  2. Add an asp:Content control for each asp:ContentPlaceHolder control in the .master file.
  3. Set the ContentPlaceHolderID attribute of the asp:Content to the ID of the corresponding asp:ContentPlaceHolder in the .master file.
  4. Add the page-specific content to the asp:Content controls.
Figure 1-1 shows the output of the master/content page in our example. Example 1-1 shows the .master file, and Example 1-2 shows the .aspx file of our example.
Figure 1-1: Quick master page example output
Implementing a basic master/content page arrangement requires no coding. The .master file consists of an <%@ Master…%> directive at the top of the page instead of an <%@ Page…%> directive and the common HTML (and server controls if required). In addition, it contains one or more asp:ContentPlaceHolder controls that reserve the space for the page-specific content. At a minimum, the ID and Runat attributes must be set, with the ID attribute being set to a unique identifier.
	<asp:ContentPlaceHolder ID="PageBody" Runat="server" />
Optionally, the asp:ContentPlaceHolder control can contain default content that is displayed if a content page does not provide any content for the placeholder.
	<asp:ContentPlaceHolder ID="PageBody" Runat="server" >
		 <div align="center">
              <br />
			  <br />
			  <h4>Default Content Displayed When No Content Is Provided In
                        Content Pages</h4>
         </div>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Extending a Master Page's Content to Include Content for Other Application Pages
You have a master page that provides the basic content for some of your pages but you would like to extend the master page to include additional content for other pages. You might want to do this, for example, when you want the login page of your application to appear one way and the pages that follow it to appear in another way that builds on the appearance of the login page.
Nest master pages as outlined here. Create the base master page that contains the minimum content used by content pages and then create the content pages that require the content of the base master page. Next, create another master page that references the base master page and adds additional content required for other pages. Now, create content pages that require the content of master pages and reference the second master page.
In the .master file of the base master page:
  1. Add the HTML that is common for your application pages.
  2. Add an asp:ContentPlaceHolder control for each portion of the page that will have page-specific content.
  3. Set the ID attributes to unique identifiers.
In the .aspx file of the pages that will use the base master page:
  1. Set the MasterPageFile attribute of the @ Page directive to the name of the .master file of the base master page.
  2. Add an asp:Content control for each asp:ContentPlaceHolder control in the .master file of the base master page.
  3. Set the ContentPlaceHolderID attribute of the asp:Content to the ID of the corresponding asp:ContentPlaceHolder in the master page.
  4. Add the page-specific content to the asp:Content controls.
In the .master file of the second master page:
  1. Set the MasterPageFile attribute of the @ Master directive to the name of the .master file of the base master page.
  2. Add the additional HTML that is common for the second type of application pages.
  3. Add an asp:ContentPlaceHolder control for each portion of the page that will have page-specific content.
  4. Set the ID attribute to a unique identifier.
In the .aspx file of the pages that will use the second master page:
  1. Set the MasterPageFile attribute of the @ Page directive to the name of the second
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Changing Which Master Page Is Used Without Modifying All Affected Application Pages
You want to use the same master page for all pages in a section of your application, but you want the ability to change which master page is used without having to modify all of the affected pages, something you cannot do with the more traditional master/content page approaches described in the previous recipes in this chapter.
Implicitly assign a master page to a content page as follows:
  1. Create a new folder within your application.
  2. Create the master page your application will be using.
  3. Place all pages that will be using the master page in the folder.
  4. Create a web.config file that contains a <pages> element with the masterPageFile attribute set to the name of the .master file and place it in the folder.
Example 1-5 shows the web.config file used to set the master page implicitly, and Examples 1-6 and 1-7 show the .master and .aspx files for our example.
In some applications, it is desirable to use the same master page for a large number of content pages and, at the same time, to be able to change to another master page without having to edit all of the pages in the application. ASP.NET 2.0 provides the ability to assign the master page implicitly to content pages by using the new masterPageFile attribute of the <pages> element in the web.config file. Setting the masterPageFile attribute to the name of a .master file assigns the master page to all content pages in the folder where the web.config file is located. This assigns the master page to all content pages in all subfolders unless another web.config file in a subfolder overrides the setting.
ASP.NET provides a lot of flexibility when using this approach. Any content page can still explicitly set the MasterPageFile attribute in the @ Page directive, as described in Recipe 1.1, which will override the setting in the web.config file. This is convenient when you have a small number of pages that need to be handled differently; however, this can become confusing when the assignment of a master page is changed in the web.config file and the developer is expecting it to affect all pages.
Implicitly assigning a master page using this approach will not work for nested master pages. If a nested master page is included without explicitly setting the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting the Master Page at Runtime
You have an application where you need to change the assignment of the master pages used at runtime.
Create the desired master/content pages as described in Recipes 1.1 and 1.2. In the Page_ PreInit event handler of code-behind for the content pages, set the Page.MasterPageFile property to the name of the desired .master file.
Example 1-8 shows the .aspx file, and Examples 1-9 and 1-10 show the VB and C# code-behind files for our application.
Many applications need the ability to change the appearance of the rendered pages as a function of many factors such as a different look for the seasons or for client branding. Using master pages and changing the assigned master page at runtime can meet the requirements of these applications.
With ASP.NET 2.0, the Page class has a new MasterPageFile property that can be set at runtime to change the master page used to render the content page. The MasterPageFile property must be set before ASP.NET begins processing the page. The Page_PreInit event occurs immediately before the page processing occurs and is the last opportunity to change the master page that will be used to render the page.
Setting the MasterPageFile property at any point in the page processing after the Page_PreInit event results in an exception being thrown, indicating the MasterPageFile property cannot be set after the Page_PreInit event.
The Page class has a new read-only Master property that can be used to access the MasterPage object. Through the MasterPage object, you can access any public properties or methods of the master page. If you have added public properties or methods to your master pages that you need to access in your content pages, you will need to cast the MasterPage object to the class type of your master page as shown below for a pageHeading property.

	CType(Page.Master, ASPNetCookbookVB_master).pageHeading = "Test Heading"

	((ASPNetCookbookCS_master)Page.Master).pageHeading = "Test Heading";
In our example, we have stored the name of the master page that will be set at runtime in the web.config as shown below. In your application, you might want to obtain the master page information from a database or any other data store that your application needs:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Tabular Data
When it comes to displaying tabular data, ASP.NET can save you a lot of time, provided you play your cards right. If you want to display data from a database in a table and you're not concerned about performance or your ability to control the arrangement of the data items within the display, you can whip up something with the GridView control in minutes using a few lines of code. Alternatively, if you're more inclined to control the tabular display, you can shape and mold the template-driven Repeater and DataList controls beyond recognition and still not step far outside a well-trodden path. But like everything else in ASP.NET, you have to know where to start and what the trade-offs are. For instance, it's helpful to know how and when the GridView control begins to fall short of the mark. That knowledge will save you the trouble of having to retrace your steps later to implement another tabular control altogether, something we've had to do ourselves at an inopportune moment during a hot project. The recipes in this chapter ought to get you well down the curve with displaying your tabular data and prevent you having to revisit some of our same mistakes.
For readers of the first edition of the ASP.NET Cookbook, you should know that we have revised this chapter to incorporate the latest enhancements to ASP.NET 2.0, including, for example, updating all the code to leverage the latest techniques as well as adding several strategies for taking best advantage of the new GridView control.
While on the subject of the GridView control, you might also have the impression that the new GridView control is the all-in-one solution for displaying tabular data. We do not hold with this view; for one thing, the server processing required to build the applicable output is large and may not always be the best approach for your application. What's more, the GridView does not afford the flexibility that its predecessors, particularly the DataGrid, offer in terms of controlling custom paging. The GridView is a useful new control. But, lest you apply GridView too broadly to your code, it helps to know its strengths and limitations as we will lay out in the chapter's first recipe.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
When it comes to displaying tabular data, ASP.NET can save you a lot of time, provided you play your cards right. If you want to display data from a database in a table and you're not concerned about performance or your ability to control the arrangement of the data items within the display, you can whip up something with the GridView control in minutes using a few lines of code. Alternatively, if you're more inclined to control the tabular display, you can shape and mold the template-driven Repeater and DataList controls beyond recognition and still not step far outside a well-trodden path. But like everything else in ASP.NET, you have to know where to start and what the trade-offs are. For instance, it's helpful to know how and when the GridView control begins to fall short of the mark. That knowledge will save you the trouble of having to retrace your steps later to implement another tabular control altogether, something we've had to do ourselves at an inopportune moment during a hot project. The recipes in this chapter ought to get you well down the curve with displaying your tabular data and prevent you having to revisit some of our same mistakes.
For readers of the first edition of the ASP.NET Cookbook, you should know that we have revised this chapter to incorporate the latest enhancements to ASP.NET 2.0, including, for example, updating all the code to leverage the latest techniques as well as adding several strategies for taking best advantage of the new GridView control.
While on the subject of the GridView control, you might also have the impression that the new GridView control is the all-in-one solution for displaying tabular data. We do not hold with this view; for one thing, the server processing required to build the applicable output is large and may not always be the best approach for your application. What's more, the GridView does not afford the flexibility that its predecessors, particularly the DataGrid, offer in terms of controlling custom paging. The GridView is a useful new control. But, lest you apply GridView too broadly to your code, it helps to know its strengths and limitations as we will lay out in the chapter's first recipe.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Selecting the Right Tabular Control
You want to use an ASP.NET control to display some data in a tabular format.
Use a Repeater, DataList, DataGrid, or GridView control. Always choose the smallest and fastest control that meets your needs, which invariably will be influenced by other criteria as in these examples:
If you need a quick and easy solution
Use a GridView.
If you need a lightweight read-only tabular display
Use a Repeater.
If you need your solution to be small and fast
Use a Repeater (lightest) or DataList (lighter).
If you want to use a template to customize the appearance of the display
Choose a Repeater or DataList.
If you want to select rows or edit the contents of a data table
Choose a DataList, a DataGrid, or a GridView.
If you want built-in support to sort your data by column or paginate its display
Choose a GridView.
If you want to use custom pagination
Choose a DataGrid.
ASP.NET provides four excellent options for displaying tabular data: Repeater, DataList, DataGrid, and GridView. Each comes with trade-offs. For instance, the GridView control is versatile, but you can pay a price in terms of performance. On the flip side, the Repeater control is lighter weight but is for read-only display; if you later decide you need to edit your data, you will have to rework your code to use the DataList, DataGrid, or GridView control instead (unless, of course, you want to embark on your own custom coding odyssey).
The impact on performance is because ASP.NET creates a control for every element of a DataGrid and GridView control, even white space, which is built as a Literal control. Each of these controls is responsible for rendering the appropriate HTML output. The DataGrid and the GridView are, therefore, the heavyweights of the grid control group because of the server processing required to build the applicable output. The DataList is lighter and the Repeater lighter still.
Table 2-1 summarizes the built-in features supported by the tabular controls and only includes controls that support data binding. (A standard Table control is not included because it does not inherently support data binding though individual controls placed in a table can be data bound.) With custom code, there are almost no limits to what you can do to modify the behavior of these controls.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating a Quick-and-Dirty Tabular Display
You want to display data from a database in a table, and you're not overly concerned about performance or your ability to control the arrangement of the data items within the display.
Use a GridView control and bind the data to it.
In the .aspx file, add the GridView control responsible for displaying the data.
In the code-behind class for the page, use the .NET language of your choice to:
  1. Create a SqlDataSource.
  2. Set the ConnectionString, DataSourceMode, ProviderName, and SelectCommand properties of the SqlDataSource.
  3. Assign the data source to the GridView control and bind it.
Figure 2-1 shows the appearance of a typical GridView in a browser. Examples 2-1 through 2-3 show the .aspx and VB and C# code-behind files for the application that produces this result.
Figure 2-1: Quick-and-dirty GridView output
Implementing a simple GridView requires little coding. You must first add a GridView control to the .aspx file for your application and set a few of its attributes, as shown in Example 2-1. The GridView control has many attributes you can use to control the creation of a GridView object, but only three are required for this example: the id, runat, and AutoGenerateColumns attributes. The id and runat attributes are required by all server controls. When the AutoGenerateColumns attribute is set to True, it causes the GridView to create the required columns automatically along with their headings from the data source.
The code required to read and bind the data to the GridView goes into the code-behind class associated with the .aspx file as shown in Examples 2-2 (VB) and 2-3 (C#). In our example, this code is placed in the Page_Load method for convenience of illustration. It creates a SqlDataSource, sets the properties to define the source of the data and the SELECT command to retrieve the data from the database, and binds the data source to the GridView control. When the DataBind method of the GridView method is executed, the data source opens a connection to the database, retrieves the data, closes the connection to the database, and then binds the data to the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Enhancing the Output of a Tabular Display
You need to display data from a database in a way that lets you organize and enhance the output beyond the confines of the DataGrid or GridView control's default tabular display. Selecting and editing the data are unimportant as is navigating through the data.
Use a Repeater control with templates and then bind the data to the control.
In the .aspx file, add a Repeater control and the associated templates for displaying the data.
In the code-behind class for the page, use the .NET language of your choice to:
  1. Create a SqlDataSource.
  2. Set the ConnectionString, DataSourceMode, ProviderName, and SelectCommand properties of the SqlDataSource.
  3. Assign the data source to the Repeater control and bind it.
Figure 2-2 shows the appearance of a typical Repeater in a browser. Examples 2-4, 2-5 through 2-6 show the .aspx and code-behind files for an application that produces this result.
Figure 2-2: Using templates with Repeater control display output
When your primary aim is to organize and enhance the output beyond the confines of the DataGrid and GridView control's default tabular display, the Repeater control is a good choice because, unlike a DataGrid or GridView, it has associated templates that allow you to use almost any HTML to format the displayed data. It has the advantage of being relatively lightweight and easy to use. When using Repeater, however, you should know about a handful of nuances that can make life easier and, in one instance, enhance performance.
Example 2-4 shows one of the most common approaches to using the Repeater control, which is to place the asp:Repeater element in a table and use its HeaderTemplate, ItemTemplate, and AlternatingItemTemplate attributes to format the displayed data as rows in the table.
A HeaderTemplate is used to define the header row of the table. In this example, the header is straight HTML with a single table row and three columns.
An ItemTemplate formats the even-numbered rows of data, and an AlternatingItemTemplate formats the odd-numbered rows. For both templates, a single row in the table is defined with the same three columns defined in the header template. In each of the three columns, data-binding statements (described later) define the data to be placed in each of the columns. The only differences between
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Displaying Data from an XML File
You want a quick and convenient way to display data from an XML file.
Use a DataGrid control and the ReadXml method of the DataSet class.
In the .aspx file, add a DataGrid control for displaying the data.
In the code-behind class for the page, use the .NET language of your choice to:
  1. Read the data from the XML file using the ReadXml method of the DataSet class.
  2. Bind the DataSet to the DataGrid control.
Figure 2-3 shows the appearance of a typical DataGrid in a browser. Example 2-7 shows the XML used for the recipe. Examples 2-8, 2-9 through 2-10 show the .aspx and code-behind files for an application that produces this result.
Figure 2-3: DataGrid with XML data output
The Page_Load method in the code-behind, shown in Examples 2-9 (VB) and 2-10 (C#), reads the data from the XML file using the ReadXml method of the DataSet class and then binds the DataSet to the DataGrid control.
Datasets are designed to support hierarchical data and can contain multiple tables of data. Because of this support, when data is loaded into the dataset, it is loaded into a Tables collection. In this example, a single node in the XML is called Book. The DataSet will automatically load the XML data into a table named Book. When binding the data to the DataGrid, you must reference the desired table if the DataSet contains more than one table. Reference the table by name instead of by index because the index value can change if the structure of the data changes.
The DataGrid control is one of the more flexible controls provided with ASP.NET. It outputs a complete HTML table with the bound data displayed in its cells. When used with a rich data source, such as a data reader, a DataTable, or a DataSet, the DataGrid can automatically generate columns for the data, complete with column headers (see Recipe 2.2 for an example using a GridView but in which you can easily substitute a DataGrid instead). Unfortunately, its default appearance and automatic behavior rarely meet the needs of a project. In this section, we discuss some ways to make changing the default appearance and behavior a little easier, especially as it relates to displaying XML data.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Displaying an Array as a Group of Checkboxes
You have data in an array that needs to be displayed as a group of checkboxes.
Use a CheckBoxList control and bind the array to it.
Add a CheckBoxList control to the .aspx file.
In the code-behind class for the page, bind the array to the CheckBoxList control.
Figure 2-4 shows the appearance of a typical CheckBoxList in a browser, with a couple of checkboxes preselected. Examples 2-11, 2-12 through 2-13 show the .aspx and code-behind files for an application that produces this result.
Figure 2-4: CheckBoxList with array data output
The CheckBoxList control simplifies the job of generating a list of checkboxes. Here's a rundown of some of the attributes that control the checkbox display. In the example that we developed for this recipe, we have placed a CheckBoxList control in a Table cell to control its position on the form as shown in Example 2-11.
The RepeatColumns attribute of the CheckBoxList control is used to set the number of columns in which the checkboxes are to be displayed.
The RepeatDirection attribute is set to Horizontal, which displays the checkboxes in rows from left to right and then top to bottom. This attribute can also be set to Vertical to display the checkboxes in columns from top to bottom and then left to right.
The RepeatLayout attribute is set to Table, which causes the CheckBoxList control to output an HTML table that contains the checkboxes. Using Table ensures the checkboxes are aligned vertically. This attribute can be set to Flow, which causes the CheckBoxList control to output a <span> element for the checkboxes with <br> elements, thus placing the checkboxes in rows. In this case, unless all of your data is the same size, the checkboxes will not be aligned vertically.
The CssClass attribute controls the format of the text displayed with the checkboxes, and the width attribute sets the width of the generated HTML table.
The styles attribute can be used to format the data in any manner supported by inline HTML styles. If you're considering using inline styles though, remember that some older browsers do not fully support them.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Displaying Data from a Hashtable
You have data in a Hashtable, a class that provides the ability to store a collection of key/value pairs, and you want to display the data in a columnar table.
Use a DataList control and bind the Hashtable to it.
Add a DataList control to the .aspx file, being careful to place it in a Table cell to control its position on the form.
In the code-behind class for the page, use the .NET language of your choice to:
  1. Define the Hashtable as the data source for the DataList control.
  2. Set the control's key and value.
  3. Bind the Hashtable to the DataList control.
Figure 2-5 shows the appearance of a typical DataList within a browser that has been bound to a Hashtable filled with, in our case, book data. Examples 2-14, 2-15 through 2-16 show the .aspx and code-behind files for an application that produces this result.
The DataList control can display almost any data type in various ways using its available templates and styles. Templates are available for the header, footer, items, alternating items, separators, selected items, and edit items to define and organize the data to output. Styles are available for each of the templates to define how the content appears.
In this example, an asp:DataList control is placed in a Table cell to control its position on the form, as shown in Example 2-14. The RepeatColumns attribute of the control defines the number of columns that should be output, which in this case is 4.
Figure 2-5: DataList with Hashtable data output
The RepeatDirection attribute indicates that the data should be output horizontally, which displays the data in rows from left to right and then top to bottom. The RepeatLayout attribute indicates the data should be output in an HTML table, which provides the greatest flexibility in arranging the data items.
The HeaderTemplate element defines a simple line of text to be used as a header for the data list. The HeaderTemplate can contain any HTML and ASP.NET controls.
The HeaderStyle element defines the positioning of the header as well as the stylesheet class used to define the text formatting. A large number of style attributes are available to format the header data.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding Next/Previous Navigation to a DataGrid
You need to display data from a database in a table; the database has more rows than can fit on a single page, so you want to use next/previous buttons for navigation.
Use a DataGrid control, enable its built-in pagination features, and then bind the data to it.
Add a DataGrid control to the .aspx file, and use its AllowPaging and other related attributes to enable pagination.
In the code-behind class for the page, use the .NET language of your choice to:
  1. Create a routine that binds a DataSet to the DataGrid in the usual fashion.
  2. Create an event handler that performs the page navigation, for example, one that handles the PageIndexChanged event for the DataGrid and rebinds the data.
Figure 2-6 shows the appearance of a typical DataGrid within a browser with next/previous navigation. Examples 2-17, 2-18 through 2-19 show the .aspx and code-behind files for an application that produces this result.
Figure 2-6: DataGrid with next/previous navigation output
The DataGrid control includes the ability to perform pagination of the data that is displayed in the grid; using the built-in pagination requires little code. Pagination is enabled and configured by the attributes of the DataGrid element:
	AllowPaging="True"
	PageSize="5"
	PagerStyle-Mode="NextPrev"
	PagerStyle-Position="Bottom"
	PagerStyle-HorizontalAlign="Center"
	PagerStyle-NextPageText="Next"
	PagerStyle-PrevPageText="Prev"
Setting the AllowPaging attribute to True enables paging for the DataGrid, and the PageSize attribute defines the number of rows that will be displayed in a single page. Setting the PageStyle-Mode attribute to NextPrev enables the output of the Next/Prev controls (see Recipe 2.9 for other uses of this attribute).
The remaining attributes define how the pagination controls look. PagerStyle-Position defines the location of the Next/Prev controls. Valid values include Bottom, Top, and TopAndBottom. PagerStyle-HorizontalAlign defines the horizontal positioning of the Next/Prev controls. Valid values include Left, Center, Right, and NotSet. NotSet is effectively the same as Left
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding First/Last Navigation to a DataGrid
You need to display data from a database in a table, but the database has more rows than will fit on a single page, and you want to use first/last buttons along with next/previous buttons for navigation.
Use a DataGrid control, add first/last and next/previous buttons (with event handlers for each one), and then bind the data to it.
In the .aspx file:
  1. Add a DataGrid control to the .aspx file.
  2. Add a row below the DataGrid with first/last and next/previous buttons for navigation.
In the code-behind class for the page, use the .NET language of your choice to:
  1. Create a routine that binds a dataset to the DataGrid in the usual fashion.
  2. For each of the four buttons, create an event handler to handle the button's click event, perform the requisite page navigation, and rebind the data.
Figure 2-8 shows the appearance of a typical DataGrid within a browser with first/last and next/previous buttons for navigation. Examples 2-20, 2-21 through 2-22 show the .aspx and code-behind files for an application that produces this result.
Figure 2-8: DataGrid with first/last and next/previous navigation output
The main theme of this recipe is to provide an alternative to the DataGrid control's default pagination controls and, at the same time, handle the custom paging. Setting the PagerStyle-Visible attribute to False makes the pager invisible in a DataGrid control, allowing you to implement your own user interface for the pagination controls. (The pager is the element on the DataGrid control that allows you to link to other pages when paging is enabled.) When the pager is invisible, some appearance-related attributes for the pager are not required and can be eliminated, specifically PagerStyle-Position, PagerStyle-HorizontalAlign, PagerStyle-NextPageText, and PagerStyle-PrevPageText. Adding a row below the DataGrid to hold the four navigation buttons (Next, Prev, First, and Last) is a key ingredient.
In the application we have developed for this recipe, we added four event handler routines to the code-behind to handle the click events for the four buttons, a handy strategy for your application as well. The event handlers alter the current page index for the grid (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding Direct Page Navigation to a DataGrid
You need to display data in a table, but the database that stores it has more rows than can fit on a single page, and you want to allow the user to select the page to display.
The simplest solution is to use a DataGrid control and its PagerStyle-Mode and PagerStyle-PageButton attributes to enable page selection. This approach produces output like that shown in Figure 2-9. To create an application that employs this approach, start by implementing Recipe 2.7 with the changes to the DataGrid tag shown here:
	PagerStyle-Mode="NumericPages"
	PagerStyle-PageButtonCount="5"
Figure 2-9: Output of simple solution to DataGrid direct paging
A more flexible solution is to hide the pager provided by the DataGrid control and implement your own user interface for the pagination controls. This approach allows the user, for example, to input a page number in a text box and then click a button to display the data as shown in Figure 2-10. Examples 2-23, 2-24 through 2-25 show the .aspx and code-behind files for an application that produces this result.
Figure 2-10: Custom direct page navigation with a DataGrid output
In the simple solution, setting the PagerStyle-Mode attribute to NumericPages causes the DataGrid to be rendered with page number buttons for navigating through the grid. The PagerStyle-ButtonCount attribute defines the number of "page buttons" that are output. If more pages are available than can be displayed, an ellipsis (…) is displayed at the end(s) of the page buttons containing additional pages. As shown in Figure 2-9, additional pages of data are available beyond Section 1.3. Clicking on the ellipsis will update the data in the DataGrid and display the next block of available pages for navigation. In our example, clicking on the ellipsis will cause Section 1.3.3 to be displayed in the DataGrid and Section 1.3.3, Section 1.3.4, Section 1.4, Section 1.4.2–Section 1.4.4 will be available for direct navigation.
The more flexible solution enables paging in the grid but, with the code shown next, hides the pager provided by the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Sorting Data in Ascending/Descending Order Within a DataGrid
You are displaying a table of data in a DataGrid, and you want to let the user sort the data and change the sort order by clicking on the column headers.
Enable the DataGrid control's sorting features, and add custom coding to support the sorting along with an indication of the current sort column and order.
In the .aspx file, enable the DataGrid control's sorting features.
In the code-behind class for the page, use the .NET language of your choice to:
  1. Create a data-binding method (bindData in our example) that does the following:
    1. Generates the SQL statement required to get the data from the database with an ORDER BY clause based on the value of the sortExpression parameter
    2. Fills a DataTable with the ordered data from the database
    3. Outputs an image indicating the sort column and sort order beside the current sort column heading
  2. Call the data-binding method from the Page_Load method (to support the initial display of the grid) and from the event that is fired when the user clicks on a column header (the dgBooks_SortCommand event in our example).
Figure 2-11 shows the appearance of a typical DataGrid sorted by title in ascending order, the information in the first column. Examples 2-26, 2-27 through 2-28 show the .aspx and code-behind files for an example application that produces this result.
Figure 2-11: DataGrid with ascending/descending sorting output
The DataGrid control provides the basic plumbing required to support sorting. It will generate the links for the column headers to raise the SortCommand server-side event when a column header is clicked. The DataGrid does not provide the code required to perform the actual sorting, but very little code is required to complete that job.
To enable sorting, the AllowSorting attribute of the DataGrid element must be set to True. In addition, the SortExpression attribute of the BoundColumn element must be set to the expression that will be used in your code to perform the sorting. This would normally be set to the name of the database column displayed in the DataGrid column; however, it can be set to any value required by your code to perform the sorting.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Combining Sorting and Paging in a DataGrid
You are implementing a DataGrid with sorting and pagination, and you are having trouble making the two features work together.
Enable the sorting features of the DataGrid control, and add custom code to support the sorting along with an indication of the current sort column and order (see Recipe 2.10 for details). Next, with pagination enabled, add a small amount of custom code to track the sort column and order so they can be maintained between client round trips and used any time rebinding is required. Figure 2-12 shows a typical DataGrid with this solution implemented. Examples 2-29, 2-30 through 2-31 show the .aspx file and code-behind files for an application that produces this output.
Figure 2-12: Combining sorting and paging in a DataGrid output
Getting sorting and paging to work at the same time is a notorious problem with a DataGrid. The key to making it all work is to track the sort column and order so they can be used any time rebinding is required, whether because of a page change or a sort command. Likewise, it is useful to put the sort column and order data in the view state so they are properly maintained between client round trips.
The DataGrid provides the basic plumbing for sorting and paging the data displayed in the grid. The DataGrid provides a property (CurrentPageIndex) that is always available to indicate which page is to be displayed. Unfortunately, the DataGrid provides no information regarding the sort column or order, forcing the programmer to track this information outside of the DataGrid so it will be available when performing pagination operations.
The application we've developed for this recipe should give you a good idea of how to handle sorting and paging simultaneously. It tracks the sort column and order so the proper data can be bound to the DataGrid any time rebinding is required, for example, when the user clicks on a row header to resort a column or selects a page from the DataGrid control's built-in navigation control. Refer to Recipes 2.9 and 2.10 for more detailed discussions of the various nuances of this recipe.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Paging Through a Record-Heavy DataGrid
You need to display a large set of data in a DataGrid, yet the user must be able to page through it quickly. This approach is beneficial anytime you have to navigate through thousands of records.
Use custom paging with a DataGrid and, using a stored procedure, read from the database only the data that is needed for a given page. An example of the output that can be achieved with this approach is shown in Figure 2-13. Examples 2-33, 2-34 through 2-35 show the .aspx and code-behind files for an application that illustrates this approach; the application uses the stored procedure shown in Example 2-32 to retrieve the data to display.
The solution we advocate for the problem of paging through large datasets requires a somewhat different approach to custom paging and managing the labels used to display the current and total pages.
Figure 2-13: Paging through a record-heavy DataGrid output
To enable paging and to allow you to control movement within the dataset when data binding, the DataGrid's AllowPaging and AllowCustomPaging attributes must be set to True. When AllowCustomPaging is set to False (the default), the DataGrid assumes that all of the data that can be displayed in all pages is present in the data source, and it calculates the group of records to display from the CurrentPageIndex and PageSize attributes. When AllowCustomPaging is set to True, the DataGrid expects only one page (as defined by the PageSize attribute) to be present in the data source and you are responsible for filling the data source with the proper page of data.
	<asp:DataGrid ID="dgBooks" runat="server"
					 BorderColor="#000080"
					 BorderWidth="2px"
					 AutoGenerateColumns="False"
					 Width="90%"
					 HorizontalAlign="Center"
					 AllowPaging="True"
					 AllowCustomPaging="True"
					 PageSize="10"
					 PagerStyle-Visible="False">
For this example, the internal paging controls of the DataGrid are not used, so the PagerStyle-Visible attribute is set False to hide the DataGrid's pager control.
A pair of labels is used to display the current page and total number of pages available. In addition, four buttons are used to provide navigation (First, Prev, Next, and Last).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Editing Data Within a DataGrid
You want to allow the user to edit the data within the table displayed by a DataGrid.
Add an EditCommandColumn column type to the DataGrid control's display to enable editing of the data fields of each record. A typical example of normal display mode output is shown in Figure 2-14, and an example of edit mode output is shown in Figure 2-15. Examples 2-36, 2-37 through 2-38 show the .aspx and code-behind files for the application that produces this result.
Figure 2-14: DataGrid with editing—normal mode
Figure 2-15: DataGrid with editing—row edit mode
This recipe uses the built-in editing facilities of the DataGrid control, in particular the EditCommandColumn column type, which provides Edit command buttons for editing data items in each row of a DataGrid. The EditText, CancelText, and UpdateText properties define the text to be output for the Edit command button's Edit, Cancel, and Update hyperlinks, respectively.
	<asp:EditCommandColumn ButtonType="LinkButton"
							  EditText="Edit"
							  CancelText="Cancel"
							  UpdateText="Update" />
The ButtonType attribute defines the type of button to output. You can specify LinkButton, which provides hyperlinked text, or PushButton, which outputs an HTML button.
The Edit command button's EditText, CancelText, and UpdateText properties can be set to HTML. For example, to output an image for the links, you can use <img src="images/buttons/editButton.gif" border="0" alt="Edit"/>.
In our example that implements this solution, three columns are defined for the DataGrid. The first uses an asp:BoundColumn element with the ReadOnly attribute set to True to prevent users from editing the field contents:
	<asp:BoundColumn DataField="SectionNumber"
						ItemStyle-HorizontalAlign="Center"
						HeaderText="Section"
						ReadOnly="True" />
The second column uses an asp:TemplateColumn element to define a layout template for normal display