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

Beginning ASP.NET 2

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

Reading Data

Figure 7-25

Figure 7-26

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

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

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

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

239

Chapter 7

Figure 7-27

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-28), and in the Properties window change RepeatColumns to 3 and the RepeatDirection to Horizontal.

Figure 7-28

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

240

Reading Data

Figure 7-29

12.Delete the text “Notes:”, 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. Delete the text and label that refers to the PictureURL. These actions are shown finished in Figure 7-30.

Figure 7-30

14.In the DataList control’s smart task panel (probably still open), click End Template Editing. The page will look as follows in Source View:

241

Chapter 7

<%@ Page Language=”VB” MasterPageFile=”~/site.master” AutoEventWireup=”false” CodeFile=”Gallery-AllTest.aspx.vb” Inherits=”Gallery_AllTest” title=”Untitled Page” %>

<asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”Server”>

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

<ItemTemplate>

<asp:Image ID=”Image1” runat=”server” ImageUrl=’<%# Eval(“PictureURL”, “~/MatchImages/{0}”) %>’ /><br />

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

FixtureID:

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

Uploaded By Member:

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

</ItemTemplate>

</asp:DataList>

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

SelectCommand=”SELECT [PictureURL], [Notes], [UploadedByMemberName], [FixtureID] FROM [Gallery]”>

</asp:SqlDataSource>

</asp:Content>

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

How It Works

After the fifth step 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”) %>’ />

242

Reading Data

Figure 7-31

The problem is that an ASP.NET 2.0 page will, by default, look for an image file in the same folder as itself. The images are kept in a different folder named MatchImages. So, you can use a feature of the Eval method to add the relative path to the name of the picture file. You add a second argument that embellishes some text onto whatever value is provided by the database. In this case you added the path. There are two new tricks in this syntax. First, in the formatting argument you use a tilde (~) that means the root of the site. When you deploy the site to another server you will not have to change all of the paths. Second, the syntax {0} indicates the place to plug in the value that comes from the database. So syntax such as the following will be translated into C:\BegASPNET\WroxUnited\MatchImages\ aaronson.jpg for the first record before it is used as the ImageURL:

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

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

You finished the exercise by getting some practice with editing templates. Remember that you must shift into Edit Templates mode prior to making changes to the controls in a template that actually present the data. If you become perplexed by the unresponsiveness of VWD when you attempt to select or modify the Label and Image controls, you have forgotten to enter Edit Templates mode. You saw how fields could be selected and then deleted or moved.

243

Chapter 7

The DetailsView and FormView Controls

The three data-bound controls you have studied so far (GridView, DataList, and Repeater) display more than one record at a time. An alternative pair of data-bound controls display just one record at a time: DetailsView automatically creates a set of templates, whereas FormView is a blank slate upon which you build templates as desired. These are useful controls when you want to focus the user’s attention on one record or need more screen real estate to display many fields for one record. They are also the preferred controls for adding or editing a record.

Like many other data-bound controls, DetailsView and FormView can be added to the page either directly, in which case VWD kicks off the wizard to create a data source control, or can be added after a data source control is already on the page.

As you will study in Chapter 8, only DetailsView and FormView can accept the addition of new records. GridView, DataList, and Repeater can change, display, and modify existing records, but not create new records.

Both the DetailsView and FormView controls rely on templates as described in the previous section. After creating the control, open the smart task panel and click Edit Templates. The appearance will change as you enter Template Edit Mode. Figure 7-32 shows the default mode.

Figure 7-32

Figure 7-33 depicts the Template Edit mode where fields can be added, removed, or rearranged.

When displaying only one record you have to make a decision whether or not to allow navigation from record to record. If you are showing details of a record selected in a GridView control, you would not want the user to be able to navigate off to other records because that would cause a loss of synchronization with the GridView. But if the DetailsView is standing alone you can turn on paging with the checkbox in the smart task panel. The same Navigation Mode options are available as discussed for the

GridView, such as Numeric, FirstLast, and PreviousNext.

In this Try It Out you practice looking at the information of one Wrox United match at a time using

DetailsView.

244

Reading Data

Figure 7-33

Try It Out

Using DetailsView and FormView

1.Create a new page in the root of your site named Fixtures-Stacked using the master page and putting the VB code in a separate file. Switch to Design View.

2.Drag a DetailsView control from the Toolbox onto the page, as shown in Figure 7-34.

Figure 7-34

3.In the DetailsView control’s smart task panel, choose its data source to be a new data source from Database with an ID of SqlDataSource2 and using the existing Wrox United connection string. Be sure to name it SqlDataSource2 because you will add a SqlDataSource1 later. Include all of the fields from the Fixtures table.

4.Before testing the page, you need to enable paging from the DetailsView control’s smart task panel. In addition, in the Properties window, configure the Pager Settings / Mode to use

NumericFirstLast.

5.With the DetailsView control selected, in the Properties window change the LastPageText property to “Last Game of the Season” and FirstPageText property to “First Game of the Season.” Also, select the DetailsView control and make it wider by dragging its right edge to the right.

245

Chapter 7

The results are as follows:

<%@ Page Language=”VB” MasterPageFile=”~/site.master” AutoEventWireup=”false” CodeFile=”Fixtures-Stacked.aspx.vb” Inherits=”Fixtures_Stacked” title=”Untitled Page” %>

<asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”Server”>

<asp:DetailsView ID=”DetailsView1” runat=”server” AllowPaging=”True”

AutoGenerateRows=”False”

DataKeyNames=”FixtureID”

DataSourceID=”SqlDataSource2”

Height=”50px” Width=”350px”> <PagerSettings

Mode=”NumericFirstLast” FirstPageText=”First Game of the Season” LastPageText=”Last Game of the Season” />

<Fields>

<asp:BoundField DataField=”FixtureID” HeaderText=”FixtureID” InsertVisible=”False”

ReadOnly=”True” SortExpression=”FixtureID” /> <asp:BoundField DataField=”FixtureDate” HeaderText=”FixtureDate”

SortExpression=”FixtureDate” />

<asp:BoundField DataField=”FixtureType” HeaderText=”FixtureType” SortExpression=”FixtureType” />

<asp:BoundField DataField=”GoalsFor” HeaderText=”GoalsFor” SortExpression=”GoalsFor” />

<asp:BoundField DataField=”GoalsAgainst” HeaderText=”GoalsAgainst” SortExpression=”GoalsAgainst” />

<asp:BoundField DataField=”Notes” HeaderText=”Notes” SortExpression=”Notes” />

<asp:BoundField DataField=”Opponents” HeaderText=”Opponents” SortExpression=”Opponents” />

</Fields>

</asp:DetailsView>

<asp:SqlDataSource ID=”SqlDataSource2” runat=”server” ConnectionString=”<%$ ConnectionStrings:WroxUnited %>” SelectCommand=”SELECT * FROM [Fixtures]”>

</asp:SqlDataSource>

</asp:Content>

6.Run the page in your browser to observe that only one match is shown at a time (see Figure 7-35).

How It Works

The key point of this exercise is to create and view a presentation where one record is shown at a time, like the top playing card in a deck. You can use either the DetailsView or FormView; you chose DetailsView because it does an automatic default layout for you.

246

Reading Data

Figure 7-35

The modifications you made to the DetailsView control were almost the same as those for other databound controls in earlier exercises. To move through the records of games you enabled paging by checking the appropriate box in the control’s smart task panel. To enhance the user experience you specified a specific set of navigation tools in the Properties window of the control and modified their text to present a more logical user interface.

Data Source Controls with Parameters

So far in this chapter you have created pages with fixed sets of data. With parameters you can determine, dynamically, what data to display in a data-bound control. In ASP.NET 2.0, a parameter is a tag that holds a data that can be used when a control carries out its task. For example, a parameter could hold a date, and that date is used to determine which game to show in a data-bound control. This section starts with a simpler case where you will look at how you can pass a parameter between pages. In the next section you will use parameters to enable two controls to work together. As with all of ASP.NET 2.0, the implementation is made even easier with tools in VWD. You will start with a simple page that picks up a value from a querystring and uses it to find one record of a table.

A querystring is field name and value added to a HTTP request, as shown in the italic part of the following URL (the text following the question mark): www.WroxUnited.com\PlayerInformation.aspx?PlayerLastName=Smith.

When you created data source controls earlier in the chapter you saw how to add only certain columns from a table in the dialog step titled Configure the Select Statement, but the wizard button captioned WHERE was not discussed (see Figure 7-36).

247

Chapter 7

Figure 7-36

If you click the WHERE button of the wizard you get a dialog box that leads you through the options to limit the data set to only certain records. This step selects which column to use in the process of limiting records. Then the “source” drop-down list offers the choice of getting the data from a querystring. That opens a section for parameter properties. In the case shown in the shaded box above you would enter PlayerLastName. These steps add a section to the data source control called SelectParameters, as shown in the following shaded code. SelectParameters is one type of parameter; you will encounter others later in the book.

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

“SELECT * FROM [Players] WHERE ([PlayerLastName] = @PlayerLastName)”> <SelectParameters>

<asp:QueryStringParameter Name=”PlayerLastName”

DefaultValue=”XXX” QueryStringField=”PlayerLastName” Type=”String” /> </SelectParameters>

</asp:SqlDataSource>

In this code, first notice in the shaded section that a <SelectParameters> is added. This is similar to a variable that will be filled by ASP.NET 2.0 with the value of Smith that comes in when you specify a querystring, as your did earlier. Then notice in the SELECT command that VWD has made the WHERE

clause equal to a name starting with an at (@) sign. The at symbol means a parameter and in this case the parameter that holds the player’s last name. Each time the page is opened or refreshed it will search the querystring for a PlayerLastName value. Typing all of these would be a waste of time; you will instruct VWD to do it for you in the next exercise.

248