Evjen c07.tex V2 - 01/28/2008 2:01pm Page 325 Chapter 7: Data Binding in ASP.NET 3.5 If (oldExpression.IndexOf(newExpression) < 0) Then If (oldExpression.Length > 0) Then e.SortExpression = newExpression & "," & oldExpression Else e.SortExpression = newExpression End If Else e.SortExpression = oldExpression End If End Sub < /script > C# < script runat="server" > protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { string oldExpression = GridView1.SortExpression; string newExpression = e.SortExpression; if (oldExpression.IndexOf(newExpression) < 0) { if (oldExpression.Length > 0) e.SortExpression = newExpression + "," + oldExpression; else e.SortExpression = newExpression; } else { e.SortExpression = oldExpression; } } < /script > Notice the listing uses the GridView’s Sorting event to manipulate the value of the control’s SortEx- pression property. The events parameters enable you to examine the current sort expression, direct the sort, or even cancel the sort action altogether. The GridView a lso offers a Sorted event which is raised after the sort has completed. Enabling the GridView Pager The GridView also greatly improves upon another common grid navigation feature — paging. Although the implementation of paging using a DataGrid greatly simplified paging (especially in com- parison to paging in ASP), the GridView makes it even easier with its AllowPaging property. This property can be set either by adding the attribute to the GridView control in HTML mode or by check- ing the Enable Paging check box in the GridView’s smart tag. Enabling paging in the GridView control defaults to a page size of 10 records and adds the Pager to the bottom of the grid. Listing 7-28 shows an example of modifying your grid to enable sorting and paging. Listing 7 -28: Enabling sorting and paging on the GridView control < asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" AutoGenerateColumns="False" AllowSorting="True" AllowPaging="True" > 325 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 326 Chapter 7: Data Binding in ASP.NET 3.5 Enabling sorting and paging in your GridView creates a page that looks like Figure 7-17. Figure 7-17 As with the D ataGrid, the GridView allows most of the paging options to be customized. For instance, the PagersSettings - Mode attribute allows you to dictate how the grid’s Pager is displayed using t he variousPagermodesincluding NextPrevious , NextPreviousFirstLast , Numeric (the default value), or NumericFirstLast . Additionally, by specifying the PagerStyle element in the GridView, you can cus- tomize how the grid displays the Pager text, including font color, size, and type, as well as text alignment and a variety of other style options. Listing 7-29 shows how you might customize your GridView control to use the NextPrevious mode and style the Pager text using the PagerStyle element. Also, you can control the number of records displayed on the page using the GridView’s PageSize attribute. Listing 7-29: Using the PagerStyle and PagerSettings properties in the GridView control < asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" AutoGenerateColumns="False" AllowSorting="True" AllowPaging="True" PageSize="10" > < PagerStyle HorizontalAlign="Center" >< /PagerStyle > < PagerSettings Position="TopAndBottom" FirstPageText="Go to the first page" LastPageText="Go to the last page" Mode="NextPreviousFirstLast" > < /PagerSettings > 326 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 327 Chapter 7: Data Binding in ASP.NET 3.5 Figure 7-18 shows the grid after you change several style options and set the PagerSettings-Mode to NextPreviousFirstLast . Figure 7-18 The GridView has a multitude of other Pager and Pager style options that we encourage you to experi- ment with. Because the list of PagerSetting and PagerStyle options is so long, all options are not listed here. You can find a full list of the options in the Visual Studio Help documents. Additionally, the GridView control offers two events you can use to alter the standard paging behavior of the grid. The PageIndexChanging and PageIndexChanged events are raised before and after the Grid- View’s current page index changes. T he page index changes when the user clicks the pager links in the grid. The PageIndexChanging event parameters allow you to examine the value of the new page index before it actually changes or even cancel the Paging event altogether. The GridView also includes the EnableSortingAndPagingCallbacks property that allows you to indicate whether the control should use client callbacks to perform sorting and paging. Client callbacks can help your user avoid suffering through a complete page postback for operations such as sorting and paging the GridView. Instead of requiring a complete page postback, client callbacks use AJAX to perform the sort and page actions. If you are interested in learning more about other ways you can integrate AJAX into your ASP.NET applications, Chapters 19 and 20 introduce you t o the ASP.NET AJAX framework and how you can leverage its capabilities in your applications. 327 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 328 Chapter 7: Data Binding in ASP.NET 3.5 Another interesting feature of column generation is the capability to specify what the GridView should display when it encounters a Null value within the column. For an example of this, add a column using an additional < asp:BoundField > control, as shown in Listing 7-30. Listing 7-30: Using the Null value < asp:BoundField HeaderText="Region" NullDisplayText="N/A" DataField="Region" SortExpression="Region" >< /asp:BoundField > In this example, the < asp:BoundField > element displays the Region column from the Customers table. As you look through the data in the Region section, notice that not every row has a value in it. If you don’t want to display just a blank box to show an empty value, you can use some text in place of the empty items in the column. For this, you utilize the NullDisplayText attribute. The String value it provides is used for each and every row that doesn’t have a Region value. This construct produces the results illustrated in Figure 7-19. Figure 7-19 Customizing Columns in the GridView Frequently, the data in your grid is not simply text data, but data that you either want to display using other types of controls or don’t want to display at all. For instance, you have been retrieving the Cus- tomerID as part of your SELECT query and displaying it in your grid. By default, the GridView control 328 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 329 Chapter 7: Data Binding in ASP.NET 3.5 displays all columns returned as part of a q uery. But rather than automatically displaying the CustomerID, it might be better to hide t hat data from the end user. Or perhaps you are also storing the corporate URL for all your customers and want the CustomerName column to link directly to their Web sites. The GridView gives you great flexibility and power regarding how you display the data in your grid. The GridView automatically creates a CheckBoxField for columns with a data type of bit or Boolean You can edit your GridView columns in two ways. You can select the Edit Columns option from the GridView smart tag. This link allows you to edit any existing columns in your grid using the Fields dialog window, shown in Figure 7-20. From here you can change a column’s visibility, header text, the usual style options, and many other properties of the column. Figure 7-20 329 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 330 Chapter 7: Data Binding in ASP.NET 3.5 Selecting the Add New Column link from the GridView control’s smart tag displays another easy form — the Add Field dialog (shown in Figure 7-21) — with options allowing you to add completely new columns to your grid. Depending on which column field type you select from the drop-down list, the dialog presents you with the appropriate options for that column type. In this case, you want to add a hyperlink; so you select the HyperLinkField from the drop-down list. The Add Field dialog changes and lets you enter in the hyperlink information, including the URL, the data field, and a format string for the column. Figure 7-21 330 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 331 Chapter 7: Data Binding in ASP.NET 3.5 The Add Field dialog lets you select one of the field types described in the following table. Field Control Description BoundField Displays the value of a field in a data source. This is the default column type of the GridView control. CheckBoxField Displays a check box for each item in the GridView control. This column field type is commonly used to display fields with a Boolean value. HyperLinkField Displays the value of a field in a data source as a hyperlink. This column field type allows you to bind a second field to the hyperlink’s URL. ButtonField Displays a command button for each item in the GridView control. This allows you to create a column of custom button controls, such as an Add or Remove button. CommandField Represents a field that displays command buttons to perform select, edit, insert, or delete operations in a data-bound control. ImageField Automatically displays an image when the data in the field represents an image. TemplateField Displays user-defined content for each item in the GridView control according to a specified template. This column field type allows you to create a customized column field. You can also change the grid columns in the Source view. Listing 7-31 shows how you can add a Hyper- LinkField. Note that by providing a comma-delimited list of data field names, you can specify multiple data fields to bind to this column. You can then use these fields in your format string to pass two query string parameters. Listing 7-31: Adding a HyperLinkField control to the GridView < asp:HyperLinkField HeaderText="CompanyName" DataNavigateUrlFields="CustomerID,Country" SortExpression="CompanyName" DataNavigateUrlFormatString= "http://www.foo.com/Customer.aspx?id={0}&country={1}" DataTextField="CompanyName" > < /asp:HyperLinkField > Using the TemplateField Column A key column type available in the GridView control is the TemplateField column that enables you t o use templates to completely customize the contents of the column. As described earlier in the GridView section of this chapter, a control template is simply a container to which you can add other content, such as text, HTML controls, or even ASP.NET controls. The TemplateField provides you with six different templates that enable you to customize a specific area of the column or to create a mode that a cell in the column may enter, such as edit mode. The following table describes the available templates. 331 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 332 Chapter 7: Data Binding in ASP.NET 3.5 Template Name Description ItemTemplate Template used for displaying an item in the TemplateField of the data-bound control AlternatingItem- Template Template used for displaying the alternating items of the TemplateField EditItemTemplate Template used for displaying a TemplateField item in edit mode InsertItemTemplate Template used for displaying a TemplateField item in insert mode HeaderTemplate Template used for displaying the header section of the TemplateField FooterTemplate Template used for displaying the footer section of the TemplateField To use the TemplateField in a GridView, simply add the column type to your grid using the Add Field dialog as described in the previous section. After you have added the field, note that a new < asp:TemplateField > tag (like the one shown in Listing 7-32) has been added to the GridView. Listing 7-32: The GridViews TemplateField < asp:TemplateField >< /asp:TemplateField > This element serves a s the container for the various templates the column can contain. Now that you have added the column, you create your custom content. You can do this by using the template editing features of the Visual Studio 2008 design surface or by adding your own content to the TemplateField element in Source view. You can access the template editing features from the Visual Studio design surface in two ways. The first method is to right-click the GridView and choose the Column[nn] (where nn is your specific column index) option from the Edit Template option in the context menu. When you use this method, each available template for the column is displayed on the Visual Studio 2008 design surface, as shown in Figure 7-22. Figure 7-22 332 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 333 Chapter 7: Data Binding in ASP.NET 3.5 The second option is t o open the GridView control’s smart tag and select the Edit Template command. This opens a menu, shown in Figure 7-23, which allows you to select the column template you want to edit. Figure 7-23 The ItemTemplate is probably the template you will use the most because it controls the default contents of each cell of the column. Listing 7-33 demonstrates how you can use the ItemTemplate to customize the contents of the column. Listing 7-33: Using ItemTemplate < asp:TemplateField HeaderText="CurrentStatus" > < ItemTemplate > < table > < tr > < td align="center" style="width: 78px" > < asp:Button ID="Button2" runat="server" Text="Enable" / >< /td > < td align="center" style="width: 76px" > < asp:Button ID="Button3" runat="server" Text="Disable" / >< /td > < /tr > < /table > < /ItemTemplate > < /asp:TemplateField > Notice that, in the sample, the ItemTemplate contains a combination of HTML and ASP.NET controls. Figure 7-24 shows what the sample looks like when it is displayed in the browser. Because the GridView control is data-bound, you can also access the data being bound to the control using data-binding expressions such as the Eval, XPath, or Bind expressions. For instance, Listing 7-34 shows how you can add a data-binding expression using the Eval method to set the text field of the Button control. You can read more about data-binding expressions later in this chapter. Listing 7 -34: Adding a data- binding expression < asp:TemplateField HeaderText="CurrentStatus" > < ItemTemplate > < table > < tr > < td align="center" style="width: 78px" > < asp:Button ID="Button2" runat="server" Text=’ < %# "Enable " + Eval("CustomerID") % > ’/ >< /td > < td align="center" style="width: 76px" > Continued 333 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 334 Chapter 7: Data Binding in ASP.NET 3.5 < asp:Button ID="Button3" runat="server" Text=’ < %# "Disable " + Eval("CustomerID") % > ’/ > < /td > < /tr > < /table > < /ItemTemplate > < /asp:TemplateField > Figure 7-24 Other common templates are the InsertTemplate and EditTemplate. These templates are used by the grid when a grid row enters insert or edit mode. You examine inserting and editing data in the GrivView control, including using the InsertItemTemplate and EditItemTemplate, in the next section. Editing GridView Row Data Not only do users want to view the data in their browser, but they also want to be able to edit the data and save changes back to the data store. Adding editing capabilities to the DataGrid was never easy, but it was important enough that developers frequently attempted to do so. The GridView control makes it very easy to edit the data contained in the grid. To demonstrate just how easy it is, you can modify the existing grid so you can edit the customer data it contains. First, modify 334 . AutoGenerateColumns="False" AllowSorting="True" AllowPaging="True" > 32 5 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 32 6 Chapter 7: Data Binding in ASP. NET 3. 5 Enabling sorting and paging in your GridView. style="width: 76px" > Continued 33 3 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 33 4 Chapter 7: Data Binding in ASP. NET 3. 5 < asp: Button ID="Button3" runat="server" Text=’ < %#. displayed on the Visual Studio 2008 design surface, as shown in Figure 7-22. Figure 7-22 33 2 Evjen c07.tex V2 - 01/28/2008 2:01pm Page 33 3 Chapter 7: Data Binding in ASP. NET 3. 5 The second option