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

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

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

Appendix A

The font-style attribute in the CSS style sheet is overridden by the element-specific style in the page.

Exercise 2

You add a Theme=”ExerciseTheme” to the preceding page. You place the CSS style sheet from the previous exercise within the ExerciseTheme theme folder. How will the label control appear now?

Solution

The Theme attribute specifies that the page should now inherit all styles within the ExerciseTheme theme folder, but the style attribute added to the element remains, and the font appears in italic.

Exercise 3

You define a skin for all labels within the ExerciseTheme theme folder and specify the following attributes:

<asp:Label CssClass=”maintext” runat=”server” font-italic=”false”></asp:Label>

How will the label appear now?

Solution

This time around, the Label control’s italic style will override the page’s style, so you will see what is shown in Figure A-4.

Figure A-4

Chapter 6

Exercise 1

In the Chapter06 project, create a new Web Form called Lists.aspx, add a ListBox control to the page, and add three list items with values of One, Two, and Three. Add a Label control and a Button control to the page. In the Click event of the Button, display the selected value of the ListBox in the Label.

628

Exercise Answers

Solution

The controls you add to the page should be as follows:

<asp:ListBox ID=”ListBox1” runat=”server”> <asp:ListItem Text=”One” /> <asp:ListItem Text=”Two” /> <asp:ListItem Text=”Two” />

</asp:ListBox> <br />

<asp:Button ID=”Button1” runat=”server” Text=”Button” /> <asp:Label ID=”Label1” runat=”server” Text=”Label” />

For the Click event of the button, you should have the following:

protected void Button1_Click(object sender, System.EventArgs e)

{

Label1.Text = ListBox1.SelectedValue;

}

This event procedure relies on the fact that there is a property on the ListBox that identifies what the value is for the selected item — the SelectedValue property. In fact, there is also a SelectedText value, because a ListBox has both a Text and a Value property. The Text is what’s displayed, whereas the Value is stored in the page and not shown to the user. This is useful for values that come from a database, where the Value would be the ID of the item and the Text would be the description. The same is true for a DropDownList control.

Exercise 2

Modify Exercise 1 so that just selecting an item in the list posts back to the server (meaning you don’t need to click the button). You’ll need to add an event procedure to the ListBox, and in that event procedure you can use the same code from the Click event of the Button to display the selected value in the Label. Hint: The terms postback and automatic might be useful in your hunt for correct properties.

Solution

To allow the ListBox to post back automatically, you set the AutoPostBack property to True. Now when a list item is selected, the postback will happen right away, rather than waiting for a button to be clicked. On its own, this just posts back, so you also need an event procedure for the ListBox, and for this you use the SelectedIndexChanged event, which is raised when the selected item changes. The event is only raised when the selected item changes, so repeated clicking of the same item will not cause unnecessary postbacks. The event procedure should be as follows:

protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e)

{

Label1.Text = ListBox1.SelectedValue;

}

The advantage of this event over a postback from a button event is that you can have your page change depending upon the user selection. For example, you could have a grid filter the data shown depending on the value in a list box.

629

Appendix A

Exercise 3

Modify the EditSquad.aspx example so that the GridView is refreshed when a new player is added to the squad. The technique is similar to the code you already have, but you’ll need to use a different event. Remember that you can use the drop-down lists in the code view to find the events.

Solution

To refresh the GridView when a new player is added to the squad, you need to use the Inserted event. Just as when the data for a SqlDataSource control is updated, the Updated event is raised, and when a new row is inserted, the Inserted event is raised. You can create this in the same way as you did for the Updated event, and use the same code in the event procedure.

The code for the Inserted event procedure is as follows:

protected void DetailsDataSource_Updated(object sender, System.Web.UI.WebControls.SqlDataSourceStatusEventArgs e)

{

GridView1.DataBind();

}

Chapter 7

Exercise 1

Describe the general capabilities of data source and data-bound controls.

Solution

Data source controls connect to the source of data and enable communicating to the database the information for behaviors such as reading, editing, and deleting.

Data-bound controls render spaces on the page that interact with the user, either to display values or to accept input for changes to the data.

Exercise 2

Which data-bound controls render data in tables?

Solution

GridView (one datum in each cell), DataList, and Repeater (all fields of one record in each cell).

Exercise 3

Compare and contrast the DetailsView and FormView controls.

Solution

Both present data in a tabular form with only one record displayed at a time. Both controls support reading and changing values, as well as creating and deleting entire records. The DetailsView control has a built-in default template, whereas FormView has no default template.

630

Exercise Answers

Exercise 4

Describe how a GridView control can limit its records to only those that match a player’s name selected in a DropDownList of last names.

Solution

The DropDownList control displays names in its Text property, and holds the player’s ID number in the Value property. The GridView control has a SelectCommand that contains a WHERE clause that sets the ID equal to a parameter (prefaced by the @ sign). The GridView control also has a parameter tab containing a parameter that is filled with the value of the selected item of the DropDownList. Set AutoPostBack to TRUE in the DropDownList box so the following behavior is automatic:

When a user changes a selection in the DropDownList, ASP.NET 2.0 automatically places the value of that selection into the GridView control’s parameter tag, which means it will be employed in the SelectCommand WHERE clause.

ASP.NET 2.0 will then cause the GridView control to create a new request for data using the new SelectCommand.

The data returned will only have records that match the ID of the player selected in the

DropDownList.

Exercise 5

Which data source control is best suited for the Menu or SiteMapPath data-bound controls?

Solution

The SiteMapDataSource is best suited for the Menu and SiteMapPath data-bound controls because it is optimized to read the XML file holding the site description information.

Chapter 8

Exercise 1

Enabling the capability to write to a database requires changes to the properties of a data source control, a data-bound control, or both?

Solution

Both.

Exercise 2

Describe the difference between an asp:Parameter and an asp:ControlParameter.

Solution

An asp:Parameter holds the value that came from the record of the database. An asp:ControlParameter holds a value that was entered by the user into a control.

631

Appendix A

Exercise 3

What problem does the DataKeyNames property solve?

Solution

Some fields hold values that uniquely identify them among all records. When a user changes values in those fields, there is a conundrum in that ASP.NET 2.0 needs the old values in order to find the record, and the new values for the writing. DataKeyNames are those fields for which ASP.NET 2.0 will hold both original and new values. When an update is made and a change is made to an ID field, ASP.NET 2.0 uses the new value for the SET part of the command (which writes) and the old value for the WHERE part of the command (which finds the one record to change).

Exercise 4

A page needs to delete the date of birth value from one record. Which command should be used?

Solution

Update. Delete would only be used to eliminate the entire record, not just one value in the record.

Exercise 5

What tags must be added to a page to allow a GridView to create new records?

Solution

This is a trick question because a GridView cannot perform inserts. But the GridView can have a button that opens a DetailsView in Insert mode, which can create a new record.

Chapter 9

Exercise 1

Create a class and shared method (called DeliveryDate) to calculate a delivery date given the date of an order. All deliveries should be made within three days of the order. Create a class and shared method to calculate delivery date given the date of an order. All deliveries should be made within three days of the order.

Solution

public class Orders

{

public static DateTime DeliveryDate(DateTime OrderDate)

{

return OrderDate.AddDays(3);

}

}

This simply uses the AddDays method of the DateTime type to add the required number of days.

632

Exercise Answers

Exercise 2

Modify the DeliveryDate method to take into account that deliveries do not happen on the weekend.

Solution

public class Orders

{

public static DateTime DeliveryDate(DateTime OrderDate)

{

DateTime deliveryDay = OrderDate.AdddDays(3);

if (deliveryDate.DayOfWeek == DayOwWeek.Saturday)

deliveryDate = deliveryDate.AddDays(2);

else if (deliveryDate.DayOfWeek == DayOwWeek.Sunday) deliveryDate = deliveryDate.AddDays(2);

return deliveryDay;

}

}

Here the delivery date is calculated and checked to see if it falls on a Saturday or Sunday, in which case the delivery date is moved to the following Monday.

Exercise 3

Modify the DeliveryDate method to take into account that an order takes three working days to process. So orders falling on a Wednesday will be delivered on the following Monday, and orders from Thursday will be delivered on the following Tuesday.

Solution

public class Orders

{

public static DateTime DeliveryDate(DateTime OrderDate)

{

switch (OrderDate.DayOfWeek)

{

case DayOfWeek.Monday: case DayOfWeek.Tuesday: case DayOfWeek.Wednesday:

return OrderDate.AddDays(3); case DayOfWeek.Thursday:

case DayOfWeek.Friday: case DayOfWeek.Saturday:

return OrderDate.AddDays(5); default:

return OrderDate.AddDays(4):

}

}

}

633

Appendix A

This version of the method uses the switch statement to calculate different dates depending upon the day of week on which the order was placed.

Exercise 4

For each of the following Boolean expressions, say for what integer values of A each of them will evaluate to True and when they will evaluate to False:

a.

b.

c.

d.

e.

NOT A=0

A > 0 OR A < 5

NOT A > 0 OR A < 5

A > 1 AND A < 5 OR A > 7 AND A < 10

A < 10 OR A > 12 AND NOT A > 20

Solution

a. True for all integers except 0. Without the NOT, the answer would only be 0. When weyou add the NOT, it reverses to be all numbers except 0.

b. True for all integers. The left side alone would be True for all integers greater than 0 (only 0 and negative integers would be false). The right side includes all integers that are less than 5, including 0 and negative integers. With the OR clause, an integer has to be within one of the two expressions in order for the entire expression to be True. When you combine these two sets of answers, you get all integers. (The integers 1 through 4 are included by both expressions.)

c. True for integers 5 and below. Integers 6 and above will evaluate to False. The issue here is precedence between the NOT and OR operators. The NOT is only applied to the expression on the left of the OR. Think of this problem as (NOT A > 0) OR (A < 5). On the left, you have True for any numbers that are not greater than 0, so True is for 0 and negative numbers. On the right, you have True for any number that is less than 5. With the two sides of the OR combined, you have True for all negative numbers and 0, and positive numbers up to 5. Numbers greater than and including 6 are True for either side and thus resolve to False.

d. True for 2, 3, 4, 8, and 9 only. Like the previous problem, the issue is to establish the precedence of the operators. Think of this as (A > 1 AND A < 5) OR (A > 7 AND A < 10). On the left of the OR, you can see that only integers 2, 3, and 4 would fit both criteria. The right side of the OR the situation is similar: only 8 and 9 meet both criteria. When you consider the OR, you have to combine those two answer sets.

e. True for all integers 9 and below (including 0 and negatives) and for 13 through 20 inclusive. False for 10, 11, 12, and all integers above (and inclusive of) 21. Think of this problem with some parentheses. The OR is the last to be evaluated, so your parentheses are (A < 10) OR (A > 12 AND NOT A > 20). First look at the right side of the OR. Integers must meet both tests when there is an AND clause, so that would be 13 through 20 are True. Now look at the left side of the OR. Any number less than 10 will be True. The final answer is the combination of those two answer sets.

634

Exercise Answers

Chapter 10

Exercise 1

Create a new web site and a new page called CodeBehind.aspx you don’t check the box marked Placed Code in a Separate File. for that page that displays the content of the label.

with a single label, but making sure that Now create a code-behind file manually

Solution

Create a class called CodeBehind.cs. Add the following line of code to CodeBehind.aspx:

<@Page CodeFile=”CodeBehind.cs” Class=”CodeBehind” %>

In the CodeBehind.aspx file, add the following within the Page_Load event:

Label1.Text = “Hello World”;

Exercise 2

How would you go about adding an image to accompany each news item? Note that it shouldn’t display if there is no news image present for that article.

Solution

Add the following to newsusercontrol.ascx:

<span class=”newsContent”>

<asp:Image style=”float:right” ID=”NewsImage” Runat=”server”

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

</span>

Add the following event handler that is called when an item of news is bound:

void NewsItem_DataBound(object sender , System.Web.UI.WebControls.RepeaterItemEventArgs e)

DataRowView row; Image img;

if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)

{

row = (DataRowView )e.Item.DataItem;

 

if (row(“PictureUrl”).ToString().Trim() == “”)

{

img = (Image )e.Item.FindControl(“NewsImage”);

 

img.Visible = False;

 

}

 

}

 

}

 

635

Appendix A

Chapter 11

Exercise 1

Create a new user account called Admin, and make this user a member of all of the groups. Log in to the Wrox United site as Admin and test to see whether you can access all of the different pages in both the fan club and the administration section.

Solution

Launch the ASP.NET Web Site Administration Tool and configure the Admin user as shown in Figure A-5.

Figure A-5

Exercise 2

Remove the Admin user from any role other than the Administrator role and test the site again. Ensure that you can access the following pages:

Admin.aspx

EditNews.aspx

UpdateProducts.aspx

Solution

The Admin user account should now have the configuration shown in Figure A-6.

If you try to access the Wrox United site, you’ll see the links in Figure A-7 within the Administration section.

636

Exercise Answers

Figure A-6

Figure A-7

637