Cover | Table of Contents
asp:ContentPlaceHolder control for each portion of the page that will have page-specific content.ID attribute to a unique identifier.MasterPageFile attribute of the @Page directive to the name of the .master file.asp:Content control for each asp:ContentPlaceHolder control in the .master file.ContentPlaceHolderID attribute of the asp:Content to the ID of the corresponding asp:ContentPlaceHolder in the .master file.asp:Content controls.
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" />
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>asp:ContentPlaceHolder control for each portion of the page that will have page-specific content.ID attributes to unique identifiers.MasterPageFile attribute of the @ Page directive to the name of the .master file of the base master page.asp:Content control for each asp:ContentPlaceHolder control in the .master file of the base master page.ContentPlaceHolderID attribute of the asp:Content to the ID of the corresponding asp:ContentPlaceHolder in the master page.asp:Content controls.MasterPageFile attribute of the @ Master directive to the name of the .master file of the base master page.asp:ContentPlaceHolder control for each portion of the page that will have page-specific content.ID attribute to a unique identifier.MasterPageFile attribute of the @ Page directive to the name of the second <pages> element with the masterPageFile attribute set to the name of the .master file and place it in the folder.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.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.Page_ PreInit event handler of code-behind for the content pages, set the Page.MasterPageFile property to the name of the desired .master file.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.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.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";
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.GridView control.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.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.GridView control.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.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:GridView.Repeater.Repeater (lightest) or DataList (lighter).Repeater or DataList.DataList, a DataGrid, or a GridView.GridView.DataGrid.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).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.GridView control and bind the data to it.GridView control responsible for displaying the data.SqlDataSource.ConnectionString, DataSourceMode, ProviderName, and SelectCommand properties of the SqlDataSource.GridView control and bind it.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.
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.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 DataGrid or GridView control's default tabular display. Selecting and editing the data are unimportant as is navigating through the data.Repeater control with templates and then bind the data to the control.Repeater control and the associated templates for displaying the data.SqlDataSource.ConnectionString, DataSourceMode, ProviderName, and SelectCommand properties of the SqlDataSource.Repeater control and bind it.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.
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.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.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.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 DataGrid control and the ReadXml method of the DataSet class.DataGrid control for displaying the data.ReadXml method of the DataSet class.DataSet to the DataGrid control.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.
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.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.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.CheckBoxList control and bind the array to it.CheckBoxList control to the .aspx file.CheckBoxList control.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.
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.RepeatColumns attribute of the CheckBoxList control is used to set the number of columns in which the checkboxes are to be displayed.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.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.CssClass attribute controls the format of the text displayed with the checkboxes, and the width attribute sets the width of the generated HTML table.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.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.DataList control and bind the Hashtable to it.DataList control to the .aspx file, being careful to place it in a Table cell to control its position on the form.Hashtable as the data source for the DataList control.Hashtable to the DataList control.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.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.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.
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.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.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.DataGrid control, enable its built-in pagination features, and then bind the data to it.DataGrid control to the .aspx file, and use its AllowPaging and other related attributes to enable pagination.DataSet to the DataGrid in the usual fashion.PageIndexChanged event for the DataGrid and rebinds the data.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.
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"
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).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 LeftDataGrid control, add first/last and next/previous buttons (with event handlers for each one), and then bind the data to it.DataGrid control to the .aspx file.DataGrid with first/last and next/previous buttons for navigation.DataGrid in the usual fashion.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.
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.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"
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.
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.DataGrid, and you want to let the user sort the data and change the sort order by clicking on the column headers.DataGrid control's sorting features, and add custom coding to support the sorting along with an indication of the current sort column and order.DataGrid control's sorting features.bindData in our example) that does the following:ORDER BY clause based on the value of the sortExpression parameterDataTable with the ordered data from the databasePage_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).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.
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.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.DataGrid with sorting and pagination, and you are having trouble making the two features work together.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.
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.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.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.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.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.
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">
DataGrid are not used, so the PagerStyle-Visible attribute is set False to hide the DataGrid's pager control.DataGrid.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.
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" />
ButtonType attribute defines the type of button to output. You can specify LinkButton, which provides hyperlinked text, or PushButton, which outputs an HTML button.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"/>.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" />
asp:TemplateColumn element to define a layout template for normal display (ItemTemplate) and edit mode display (EditItemTemplate). The EditItemTemplate property defines an asp:TextBox
control to control the size and other aspects of the field contents. Both templates are bound to the GridView with sorting and paging.GridView and add custom coding to display the sort order in the header of the current sort column. Figure 2-16 shows a typical GridView with sorting and paging implemented. Examples 2-39, 2-40 through 2-41 show the .aspx file and the code-behind files for an application that produces this output.
DataGrid, the GridView provides the ability to perform sorting and paging without having to write any custom code. But because the GridView does not provide any indication of the current sort column or order, you may want to write a small amount of custom code to accomplish this, as described in this recipe.GridView, an excellent addition to the ASP.NET 2.0 controls, provides the ability to implement standard sorting and paging with little code. Sorting and paging are enabled by setting the AllowSorting and AllowPaging attributes to true.
<asp:GridView ID="gvBooks" Runat="Server"
AllowPaging="true"
AllowSorting="true"
ShowHeader="true"
…
ShowHeader attribute must be set to true to support sorting since the header provides the controls used to perform the sorting.HeaderText for each column that needs to support sorting cannot be set to an empty string. Otherwise, the control used to perform the sort operation for the column will not be rendered.Page_Load event handler in our application initializes the SqlDataSource and then sets the DataSourceID of our GridView to the ID of the SqlDataSource.GridView's built-in sorting and paging works only if the DataSourceID property of the GridView is set to the ID of the data source. If you use the DataSource property instead, you will have to implement all of the same event handlers that are required to perform sorting and paging with a DataGrid (see Recipe 2.11).SortExpression property of the GridView is set to an empty string and the SortDirection property is set to GridView and have its contents be updated without refreshing the whole page when the user performs a sort or paging operation.Enab