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

Beginning ASP.NET 2

.0.pdf
Скачиваний:
19
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Reading Data

7.But what if the team plays in January or February or you observe that there are no September games even though you have the ninth month in your list box? You want the pages to offer new choices in the list box automatically (dynamically). Now you will improve the ListBox control by binding it to the list of fixtures.

8.Drag a SqlDataSource control from the toolbar onto the fixtures page (the .aspx page, not the code page), as shown in Figure 7-15. You will probably have to scroll down to see it, then open its smart task panel and configure its data source. Select the WroxUnited and click Next.

Figure 7-15

9.Specify a custom SQL statement and click Next. Type in the following statement:

SELECT DISTINCT MONTH(FixtureDate) AS FixtureMonth FROM Fixtures

10.Click Next, Test Query, and finally, click Finish.

11.Now change your ListBox control in the Properties window by performing the following actions: Eliminate the DataSource value; add a DataSourceID value of SqlDataSource1; set both the DataTextField and DataValueField to FixtureMonth (see Figure 7-16). Recall that if the Properties window is not already visible (usually in the bottom right of your screen) you can bring it back by pressing F4.

Figure 7-16

229

Chapter 7

12.Last, in Source View, remove some lines in the code page that are no longer needed. Delete the lines shaded here:

Protected ListOfMonths() As Integer = {9,10,11,12}

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load

ListBox1.DataBind() End Sub

13.Run the page. Now the ListBox control only shows the months with games; 9 is left out. Months will also automatically change if the Wrox United schedule adds games in another month.

How It Works

Adding a ListBox control is easy with VWD’s drag-and-drop functionality. In the hard-coded technique you created an array of integers and filled it with what you expected would be useful values. Then down in the ListBox properties you specified that the items of the list (its DataSource) should come from the values returned by a read of the array ListOfMonths. Last, back up in the code, you added a line to the Page_Load event that instructs ASP.NET 2.0 to actually bind the data of the array to the data-bound control.

Two problems exist with this technique. First, it uses the ASP.NET version 1.1 technique of binding by explicit command. Although that works (and is the only technique for hard-coded arrays) it does not utilize the automatic binding features of version 2.0. Second, if Wrox United changes the months in which it plays, then your list box choices are out of synch.

In the second technique you created a new data source control that will read the actual months that are currently in the games list. However, those months are stored as full dates (such as 12/21/04). So you use a SQL function called MONTH to extract the number of the month from the date. And because more than one game is played in a month, you add the DISTINCT term to give you just one of each value. (These kinds of SQL tricks are discussed in Wrox’s Beginning SQL.) Now you do not need the lines to create or fill the array and you can also chuck out the binding line (ASP.NET 2.0 will do it for you when you use an ASP.NET 2.0 data source control).

Notice the subtle but important difference between two properties of the ListBox control. DataSource is used when you are binding by explicit command to an ASP.NET version 1.1 source of data. DataSourceID is employed when you use ASP.NET 2.0 automatic binding to a data source control.

The GridView Control

The GridView data-bound control provides the classic display of tabular data. Each row represents one instance or record, and each column holds one field of data. A cell within the table displays a value that is appropriate for its intersection of record and column. By default, GridView displays all of the columns that are provided by the data source control, but you’ll see how to show the user only a subset. The biggest advance in tabular data display comes when you activate two simple features of the GridView control: sorting and paging. Sorting allows the user to re-order the records according to taste. Paging allows you, as the designer, to specify the number of records to show at one time and then provide the user navigation tools to jump to different sets of records. Both of these features took hundreds of lines of

230

Reading Data

codes to get right in earlier versions of ASP.NET, so they are huge timesavers that you get for free with ASP.NET 2.0.

Like all data-bound controls the GridView control must have a data source control to provide the values. GridView was optimized to work with the data source controls optimized for tabular data, for example SQL, Access, and Data controls, as opposed to the tree data of an XML source control.

Adding a GridView Control

Of course, VWD reduces control implementation to simple drag and drop. You can add a GridView control in VWD one of three ways. The techniques in the following list increase in the number of steps required as you go down the list; drag-and-drop a field is quickest, adding the controls independently requires the most steps. However, in every case you can go back and edit a GridView control’s properties in Design View, or even modify the source code directly:

From the Data Explorer window, select and drag field names to create a GridView control and automatically create a data source control — with no questions asked.

From the toolbar, drag a GridView control to the page and let VWD walk you through the setup of a new data source control.

From the toolbar, first add a data source control then drag on a GridView control and use the nascent data source control.

Regardless of which technique you use, once the GridView control is on the page its smart task panel will open, as shown in Figure 7-17. Click the Auto Format option to quickly apply a set of colors, borders, and cell sizes. Note the first choice, the ability to remove a prior auto-formatting.

Figure 7-17

You can add or remove columns with three techniques. The easiest way is to use the smart task panel and click Edit Columns. Expand the entry for BoundField, select a field, and click Add. From the box below you can select a field and click the X button to delete (see Figure 7-18).

A second technique, while you have the Fields dialog box open, is to click the option in the bottom-left corner to Auto-Generate fields. This option will display all fields.

And last, you can switch to Source View and hand-edit the list of fields.

231

Chapter 7

Figure 7-18

Before moving on, take a look at the code that VWD builds for a GridView control. Note that a databound control such as GridView will always have a DataSourceID property that points to the data source control providing the data. Note that the DataSourceID property points to a data source control and is used here. A similarly named property, the DataSource, is used in more advanced scenarios. First, display of all fields by including setting the autogeneratecolumns property to True, as follows:

<asp:gridview id=”EmployeesTable” runat=”server” datasourceid=”EmployeesDataSource”

autogeneratecolumns=”True”

</asp:gridview>

The following syntax would only display three of the fields because you set the autogeneratecolumns to false and instead, have a set of tags called <Columns>. Within those tags you add an <asp:BoundField> tag for each field. Note that ASP.NET 2.0 uses the terms columns and fields interchangeably here.

<asp:gridview id=”EmployeesTable” runat=”server” datasourceid=”EmployeesDataSource” autogeneratecolumns=”False”

</asp:gridview>

<Columns>

<asp:BoundField HeaderText=”Hired Date” DataField=”DateHire” </asp:BoundField>

<asp:BoundField HeaderText=”First Name” DataField=”NameFirst” </asp:BoundField>

<asp:BoundField HeaderText=”Last Name” DataField=”NameLast” </asp:BoundField>

</Columns>

</asp:gridview>

232

Reading Data

Adding Paging and Sorting to a GridView Control

Designers faced an onerous task prior to ASP.NET 2.0 when they had to implement paging and sorting. The ASP.NET 2.0 design team took it upon itself to offer these features fully coded and ready to use. Select a GridView control and open its smart task panel by clicking the small triangle at the top right of the control to see checkboxes to turn on paging and sorting as shown Figure 7-19.

Figure 7-19

Turning on paging and sorting requires two prerequisites. First, the GridView control must have its DataSourceID set to a valid data source control on the page. Second, that data source control must have its EnablePaging and/or EnableSorting properties set to True. The logic is that when a user requests a sort by clicking on a GridView control, the GridView passes the request down to its data source control. The data source control revises the data and sends the new information back to the GridView control, which re-renders. Sorting also requires that fields have a header value so there is a target for users to click.

Checking sorting enables sorts on all columns. Note that 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>

233

Chapter 7

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-20.

Figure 7-20

The last entry is a setting for the number of records to show at once (PageSize). For navigation, the highest-level property is Mode, wherein you can select one of four custom sets of tools that are selfdescribing, and explained in the following list. 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.

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. We also recommend you 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 Source View.

2.Switch to (or open with Ctrl+Alt+S) the database explorer. Expand the WroxUnited.mdf, then expand Tables, and finally expand Fixtures, as shown in Figure 7-21. Select all of the fields and

234

Reading Data

drag them to 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 and close the browser.

Figure 7-21

3.Next you 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 button to delete as shown in Figure 7-22. Repeat for the GoalsAgainst column. Click OK when you are finished.

Figure 7-22

235

Chapter 7

4.Now you can go back and enable paging. In Design View, select the GridView and open its smart task panel. Turn on the checkbox for Enable Paging and then close the panel. Look in the property 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.You finish by enabling sorting. 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.

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 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 a default formatting and templates whereas 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.

236

Reading Data

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), whereas 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 once you have worked with templates (as in the next exercise) you will find the template feature is well designed.

With an understanding of templates, we can go back and make two notes. First, templates are also available in the GridView control and work the same way. Second, the difference between a DataList control and a Repeater control is that the DataList control has a set of default templates, whereas 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

The DataList Control

1.Create a simple ASP.NET 2.0 Web Form page named Gallery.aspx using our site.master and with the code placed in a separate page. Save it and then save it again as Gallery-All.aspx. Also, for this exercise you will need some images that we supply in the download. Check if you have already imported the MatchImages folder in from the download (C:\BegASPNET2\WroxUnited). If not, import it by right clicking on 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 Images and within there a series of GIF and JPG files including AddToCart.gif, ArrowFirst.gif and logo_white.jpg.

2.Start 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-23, and click Choose Data Source. Click New Data Source for the wizard to create a data source control.

Figure 7-23

3.Select Database as the source and leave the name as SqlDataSource1. Click OK. Use the WroxUnited.

4.From the Gallery table check off just five fields: PictureURL, FixtureID,

UploadedByMemberName, Notes and PictureURL, and then test the query. At this point VWD automatically creates the data source control and sets it as the source for the DataList control.

237

Chapter 7

Figure 7-24

5.Run the page in your browser to test (see Figure 7-24), 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-25. Select and then delete the line that has the text PictureURL and a Label control.

7.From the toolbar, drag an Image control into the space left by the old PictureURL field. 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-26.

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=”PictureImage” runat=”server” ImageUrl=’<%# Eval(“PictureURL”)%>’

</asp:image>

238