Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2.0 With CSharp (2006) [eng]

.pdf
Скачиваний:
75
Добавлен:
16.08.2013
Размер:
20.33 Mб
Скачать

Chapter 7

Figure 7-18

Checking sorting enables sorts on all columns. When the page is running, a user can click a second time on a column’s header to change the direction of the sort. Individual columns can be sortable or not by going to Source View and removing the SortExpression property. In the following snippet built by VWD, the Date field is not sortable but the Name field will sort because after the sort option was checked, VWD added a SortExpression property to the Name field (the shaded line):

<asp:GridView ID=”GridViewSemiSortable” runat=”server” AllowSorting=”True”

AutoGenerateColumns=”False”

DataSourceID=”SqlDataSource1”>

<Columns>

<asp:BoundField DataField=”Date” HeaderText=”FixtureDate” /> <asp:BoundField DataField=”Name”

HeaderText=”FixtureType” SortExpression=”FixtureType” />

</Columns>

</asp:GridView>

Paging requires additional design elements to offer navigation tools to the user. As soon as the paging option is checked, the GridView control has an additional panel for PagerSettings in the Properties window, as shown in Figure 7-19.

The last entry is a setting for the number of records to show simultaneously (PageSize). For navigation, the highest-level property is Mode, where you can select one of four custom sets of tools. Selecting one of these sets of tools automatically sets the remainder of the properties for PagerSettings:

NextPrevious: Displays only the Next and Previous options.

Numeric: Displays a list of page numbers, with the number of pages to display set by

PageButtonCount.

NextPreviousFirstLast: Displays only the Next, Previous, First, and Last options.

NumericFirstLast: Displays the numbers of pages and also the two terminal buttons.

228

Reading Data

Figure 7-19

Of course, you can go beyond the option packages and set any property as desired. A common modification is to substitute site-specific images for the tools. Look carefully at the text properties. Sometimes the default words do not clearly relay the intention. For example, the term “last” when working with dates could mean the last record added in time, the last event to occur, or the last page that you viewed.

In the following Try It Out, you add a GridView of games. Each row will be a record from the Fixtures table; that is, one game. Columns will hold information such as the date and opponent of the game.

Try It Out

Adding a GridView Control to Fixtures.aspx

1.Open your Fixtures.aspx page and use Design View.

2.Switch to (or open with Ctrl+Alt+S) the Database Explorer. Expand WroxUnited.mdf, expand Tables, and expand Fixtures, as shown in Figure 7-20. Select all of the fields and drag them to the bottom of the content section of the Fixtures.aspx page. VWD does all of the heavy lifting. Wait for it to finish and then run the page. Admire your work (although at this point there is no connection between the ListBox and the GridView) and close the browser.

Figure 7-20

229

Chapter 7

3.Continue in Design View and modify which fields are displayed. Looking at the scores, it might be just as good to delete those. Be sure the browser is not displaying the page, because that will lock it in VWD. Select the GridView and open its smart task panel. Click Edit Columns and in the bottom left, select the GoalsFor, and click the X icon to delete as shown in Figure 7-21. Repeat for the GoalsAgainst column. Click OK when you are finished.

Figure 7-21

4.Turn on the check box for Enable Paging and then close the smart tasks panel. Look in the Properties window to find the PageSize property that you will set to two (Wrox United doesn’t get invited to many games). Also note the section of PagerSettings. Set the mode to NumericFirstLast. Again, run in the browser, play with paging, and then close the browser.

5.Open the smart task panel and check Enable Sorting.

Because the Notes field is not logical for sorts, turn off sorting for that one field. Switch to Source View, and within the GridView control find the BoundField for Notes. Delete the entire property of SortExpression=”Notes”. Save the file and check it in your browser.

How It Works

Adding a GridView control is simplicity itself with the help of VWD. This example demonstrated removing columns with the Edit Columns feature and it is just as easy to add columns. Turning on paging is as simple is checking the option, followed by setting properties for the control in the Properties window. The PageSize property is obvious, but other settings are under the PagerSettings group. Turning on sorting was easy. Removing the sort option from one column was similarly easy. All you had to do was go to Source View and delete that field’s SortExpression property.

230

Reading Data

The DataList and Repeater Controls

The GridView control displayed data with each cell holding one piece of information (for example, the first name of employee 6). ASP.NET 2.0 offers the alternative of a table where all of the fields for one record are in one cell (one cell holds the first name, last name, ID, and date of hire, all for employee 6). Two data-bound controls render one record per cell: DataList and Repeater. The only difference is that the DataList control has default formatting and templates, but the Repeater control requires more setup by the designer.

Creating a DataList control is similar to creating a GridView control. You can drag and drop the databound control from the toolbar and a let VWD walk you through creation of a new data source control, or you can add the data source control by hand and then add the data-bound control. The DataList control’s properties support the capability to set the Layout Repeat Direction so that records are ordered to increase horizontally across the page or vertically down the page, as well as the number of columns.

Templates offer the capability to lay out the space within a cell. For example, if you want a different set of fields in each DataList cell, want to change the cell’s background to pink, and want to add a logo to each cell, you can modify the template. The exercise that follows walks you through changing a template.

Templates are invaluable, but there are several confusing points. First, templates by themselves do not display data. Rather, templates contain data-bound controls, such as labels, that do the actual display of data. Second, there are multiple templates for a given space. A DataList cell can have an Item Template (the normal display for data), an Alternating Item Template (to create every other record with a different color), a Selected Template (to change the appearance when selected), and an Edit Item template (to change the appearance during editing). Each of these templates is designed independently, as you will see. The third point of confusion is that you must enter into a specific template editing mode in order to make the changes — you cannot change a template by just selecting and modifying fields in Design View. After editing a template, you must explicitly end the template editing mode. Last, ASP.NET 2.0 uses the term style in context of templates. Styles primarily provide the properties for appearance (color, borders, and so forth), and the template primarily provides the layout of fields (but can also specify appearance). If a color or border is set in both the style and the template, the template will take precedence. It may seem that this is a minefield, but after you have worked with templates (as in the next exercise) you will find the template feature is well-designed.

Templates are also available in the GridView control and work the same way. The difference between a DataList control and a Repeater control is that the DataList control has a set of default templates, and the Repeater control is a blank space in which you must build all of the templates.

In this Try It Out, you practice using a DataList to display pictures from Wrox United matches. You will create a simple page that shows all of the pages and name it Gallery-All. Later in the chapter, you will create a more complex version as your final Gallery.aspx.

Try It Out

DataList

1.Create a simple ASP.NET 2.0 Web Form page named Gallery-all.aspx in your site’s root using the site.master and with the code placed in a separate page. Also, for this exercise, you will need some images that are supplied in the download. Check if you have already imported the

231

Chapter 7

MatchImages folder from the download (C:\BegASPNET2\WroxUnited). If not, import it by right-clicking the root of the site in Solution Explorer and using Add Existing Item. In the end, you should have below the root a folder named MatchImages, and within there a JPEG of a player in action. Note that in other parts of the book, you will also use an Images folder that holds files such as AddToCart.gif, ArrowFirst.gif, and logo_white.jpg.

2.Start in Gallery-All by dragging a DataList control from the Data section of the Toolbox to the content area. Open its smart task panel, as shown in Figure 7-22, and click Choose Data Source. Click New Data Source for the wizard to create a data source control.

Figure 7-22

3.Select Database as the source and leave the name as SqlDataSource1. Click OK. Use the WroxUnited connection string (not WroxUnited.mdf because that choice will create a new connection).

4.From the Gallery table, check the five fields: PictureURL, FixtureID, UploadedByMemberName, Notes, and PictureURL. Then click Next, test the query, and finish. You can also use the wildcard (*) to select all fields, but having them listed in the SQL statement on the page makes it a little easier for understanding and troubleshooting when you look at the source code. At this point, VWD automatically creates the data source control and sets it as the source for the DataList control.

5.Run the page in your browser to test it (see Figure 7-23), noticing that you don’t have the pictures yet. Close the browser.

6.Now you need to actually get the pictures displayed. Be sure your browser is closed and then in Design View select the DataList control, open its smart task panel, and click Edit Templates to see a screen similar to Figure 7-24. Select and then delete the line that has the text PictureURL and a Label control.

7.From the Toolbox, drag an Image control into the template just below the Picture ID field. Feel free to add a carriage return (by pressing Enter) to get the image control on its own line. On the Image control’s smart task panel, click Edit Data Bindings, and select the property ImageURL to bind to the field PictureURL, as shown in Figure 7-25.

The resulting source code follows. If you test the page in your browser, you’ll notice that you are still not there. The Image control still does not have a URL that actually points to an image:

<asp:image id=”Image1” runat=”server”

ImageUrl=’<%# Eval(“PictureURL”)%>’ />

232

Reading Data

Figure 7-23

Figure 7-24

233

Chapter 7

Figure 7-25

8.To get this to work, you must identify not only the name of the image file but also its path (folder). Staying in Source view, add the following argument to the imageURL property:

<asp:image id=”Image1” runat=”server”

ImageUrl=’<%# Eval(“PictureURL”, “~/MatchImages/{0}”) %>’ />

9.Check your page in the browser (see Figure 7-26), shout “Eureka!” and then close the browser.

10.Now make some modifications to the DataList. Back in Design View, change the layout of the DataList control. Select the DataList control (see Figure 7-27), and in the Properties window change RepeatColumns to 3 and the RepeatDirection to Horizontal.

11.You’ll finish with a little practice on templates. In Design View, select the DataList control and open its smart task panel. Click Edit Templates and, by default, you will be editing the Item template, shown in Figure 7-28.

12.Delete the “Notes:” text, but keep the label that shows the notes.

13.In the layout, move the FixtureID up higher in the template and the Member Name lower in the template. Edit the text UploadedByMemberName by adding some spaces between the words so it is easier to read. These finished actions are shown in Figure 7-29.

234

Reading Data

Figure 7-26

Figure 7-27

235

Chapter 7

Figure 7-28

Figure 7-29

14.In the DataList control’s smart task panel (which is probably still open), click End Template Editing. The page should look like the following in Source View:

<%@ Page Language=”C#” MasterPageFile=”~/site.master” AutoEventWireup=”true” CodeFile=”Gallery-All.aspx.cs” Inherits=”Gallery_All” Title=”Untitled Page” %> <asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”Server”>

<h2>

236

Reading Data

Match Images</h2>

TIO - DataList - Gallery-All<br /> <asp:DataList ID=”DataList1” runat=”server” DataKeyField=”PictureID” DataSourceID=”SqlDataSource1”>

<ItemTemplate>

PictureID:

<asp:Label ID=”PictureIDLabel” runat=”server” Text=’<%# Eval(“PictureID”) %>’></asp:Label><br />

FixtureID:

<asp:Label ID=”FixtureIDLabel” runat=”server” Text=’<%# Eval(“FixtureID”) %>’></asp:Label><br />

UploadedByMemberName:

<asp:Label ID=”UploadedByMemberNameLabel” runat=”server” Text=’<%# Eval(“UploadedByMemberName”) %>’></asp:Label><br />

Notes:

<asp:Label ID=”NotesLabel” runat=”server” Text=’<%# Eval(“Notes”) %>’></asp:Label><br />

<asp:Image ID=”Image1” runat=”server”

ImageUrl=’<%# Eval(“PictureURL”, “~/MatchImages/{0}”) %>’ /> <br /><br />

</ItemTemplate>

</asp:DataList><asp:SqlDataSource ID=”SqlDataSource1” runat=”server” ConnectionString=”<%$ ConnectionStrings:WroxUnited %>” SelectCommand=”

SELECT [PictureID], [FixtureID], [UploadedByMemberName], [Notes], [PictureURL]

FROM [Gallery]”> </asp:SqlDataSource>

</asp:Content>

15.Run the page to see the results of your work in your browser (see Figure 7-30).

How It Works

After the step 5, you had produced a page with names of picture files, not the actual images. This was because when VWD made the DataList control’s default template, it saw there was text in the PictureURL field so it created a Label control, as follows:

...

<asp:DataList ID=”DataList1” runat=”server” DataSourceID=”SqlDataSource1” RepeatColumns=”3” RepeatDirection=”Horizontal”>

<ItemTemplate>

<asp:label ID=”label1” runat=”server” Text=’<%# Eval(“PictureURL”) %>’>

</asp:Label>

In the next step, you changed the control from a Label to an Image control, as shown in the following code. This gave you an image but left the image rendered as a red x, meaning that the image could not be found.

<asp:Image ID=”Image1” runat=”server” ImageUrl=’<%# Eval(“PictureURL”) %>’ />

237