Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 9 pdf

90 318 0
Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 9 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

string connectionString = ConfigurationSettings.AppSettings["ConnectionString"]; System.Data.IDbConnection dbConnection = new System.Data.OleDb.OleDbConnection(connectionString); string queryString = "SELECT [Players].[PlayerName],[Positions].[PositionName],[Teams].[TeamName] FROM [Players], [Positions], [PlayerTeam], [Teams] WHERE (([PlayerTeam].[PlayerID] = [Players].[PlayerID]) AND ([PlayerTeam].[Position] = [Positions].[PositionID]) AND ([PlayerTeam].[TeamID] = [Teams].[TeamID]) AND ([Players].[PlayerID] = @PlayerID))"; System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand(); dbCommand.CommandText = queryString; dbCommand.Connection = dbConnection; System.Data.IDataParameter dbParam_teamID = new System.Data.OleDb.OleDbParameter(); dbParam_teamID.ParameterName = "@PlayerID"; dbParam_teamID.Value = playerID; dbParam_teamID.DbType = System.Data.DbType.Int32; dbCommand.Parameters.Add(dbParam_teamID); dbConnection.Open(); System.Data.IDataReader dataReader = dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection); return dataReader; } The GetTeamsByPlayer() method is a very simple alteration of GetPlayersByTeam() from the Teams page. The really tricky part on this page is that we need to obtain the ID of the player that the user selects. In the Team page, that was easy – we packaged up each team's ID as the CommandArgument for the LinkButton in the teams DataList. But a DataGrid won't let us do that, so we need to find another solution. Remember the fields we set up on the players DataGrid? At the left hand side there was an invisible column that contained the player ID. This is how we get it: TableCell cell = (TableCell)e.Item.Controls[0]; int SelectedPlayerID = int.Parse(cell.Text); Chapter 11 This chapter deals with tracking users across pages and looks at the ASP.NET objects that are used to enable this feature. Exercise 1 Add some text, Current Topic, and a Label control to the Chat.aspx page above the main chat box, which contains the text of the current topic (stored in the Application object). Add some default topic 693 Exercise Solutions text to the Global.asax file and also another box and button to the page, allowing you to change the current topic. Solution You should start this exercise by adding the text and Label control to the top of the page. This is a simple addition that you can do either in the Design view, HTML view, or the All view. ❑ In Design view, type some text directly below the sub-heading that says Current topic:. ❑ Drag a Label control onto the page and set its ID to lblCurrentTopic. Alternatively, enter the following code below the sub-heading: <h2>Online Chat</h2> Current topic: &nbsp; <asp:Label id="lblCurrentTopic" runat="server"> </asp:Label> <br /> In Global.asax, you need to enter code that will store the details of the default topic when the application is first started: public void Application_Start(Object sender, EventArgs e) { Application["ChatLog"] = "Hello, and welcome to the Wrox United Chat page!"; Application["CurrentTopic"] = "General free-for-all chat!"; } Back in Chat.aspx, add the following line to the Page_Load event handler: void Page_Load() { txtChatBox.Text = (string)Application["ChatLog"]; lblCurrentTopic.Text = (string)Application["CurrentTopic"]; } You can run the page at this stage and the default topic, 'General free-for-all chat!', will be displayed at the top of the page. To make this exercise interactive, you need to add a couple of controls and another event handler. Below the two buttons, you need to add another row to your table. ❑ In the first cell, enter some text to tell the user what to do (for example, Enter a new topic). ❑ In the next cell, drag a TextBox control into the cell and name it txtTopic. ❑ Add another row and in the first cell, enter a non-breaking space. In the second, add a button control with its ID set to btnUpdateTopic. Double-click this button to wire up an event handler for the click event. 694 Appendix A Alternatively, enter the following code: <asp:Button id="btnPost" onclick="btnPost_Click" runat="server" Text="Post message"></asp:Button> <asp:Button id="btnClearLog" onclick="btnClearLog_Click" runat="server" Text="Clear log"></asp:Button> <hr /> </td> </tr> <tr> <td width="150"> Enter a new topic: </td> <td> <asp:TextBox id="txtTopic" runat="server" MaxLength="100" width="402px"> </asp:TextBox> </td> </tr> <tr> <td> &nbsp; </td> <td> <asp:Button id="btnUpdateTopic" onclick="btnUpdateTopic_Click" runat="server" text="Update Topic"> </asp:Button> </td> </tr> Finally, you need to add some code to update the contents of the Application object when the button is clicked: void btnUpdateTopic_Click(object sender, EventArgs e) { Application["CurrentTopic"] = txtTopic.Text; lblCurrentTopic.Text = (string)Application["CurrentTopic"]; txtTopic.Text = ""; } Exercise 2 Add the session initialization code from the stylesheet example to your Global.asax file. Solution You'll recall that, during the CSS example, the following code was included in the Page_Load() method of Default.aspx: if (Session["SelectedCss"] == null) { if (Request.Cookies["PreferredCss"] == null) { 695 Exercise Solutions Session["SelectedCss"] = "WroxUnited.css"; } else { Session["SelectedCss"] = Request.Cookies["PreferredCss"].Value; } } This code can be shortened considerably by adding the following statement to the Global.asax file: public void Session_Start(Object sender, EventArgs e) { System.Collections.Hashtable basketTable = new System.Collections.Hashtable(); Session["Basket"] = basketTable; Session["SelectedCss"] = "WroxUnited.css"; } The code in Page_Load() method can now be changed to the following: if (Request.Cookies["PreferredCss"] != null) { Session["SelectedCss"] = Request.Cookies["PreferredCss"].Value; } Exercise 3 Add a link to the Merchandise.aspx page from the front page of the site, and then apply the stylesheet used in the Default.aspx page to all the other pages in the site. You will need to add the <link > tag to the <head > section of each page and you will need to ensure that the session initialization code is correctly configured in the Global.asax file from the previous exercise. Solution Adding the link to the Default.aspx page is quite simple – just add the following code to the list of links: <p> <asp:HyperLink id="lnkMerchandise" runat="server" NavigateUrl="Merchandise.aspx"> Merchandise </asp:HyperLink> </p> Now you can add the css link to each of the other pages in the site: <head> <link id="css" href='<%= (string)Session["SelectedCss"] %>' type="text/css" rel="stylesheet" /> </head> 696 Appendix A Having said this, it's not always quite as simple as it looks – take a look at the output of Teams.aspx when using the Away scheme and you'll notice that the red links remain red, because the color was hard- coded when the page was created. You need to remove the color information from the tag: <asp:linkbutton text='<%# DataBinder.Eval(Container.DataItem, "TeamName") %>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "TeamID") %>' id="TeamNameLink" style="color:darkred" runat="server" CommandName="ShowTeam" /> Once you delete the style="color.darkred" attribute, the links will inherit the styling defined for all hyperlinks. Players.aspx has some additional styling that will need to be amended. The font color and header bar are blue and since the theme for the site is red, white, and black, these colors need altering. First, delete all the hard-coded styles from the control – you may find that the Properties pane is the most useful tool for this. Next, you can add some custom styling. Here is some CSS code you can add to WroxUnited.css: .datatablebody { background-color:"#ffffff"; color:black; font-size:smaller; } .datatablebody td{ padding:3; } .datatablehead { background-color:"#c0c0c0"; color:black; font-weight:bold; } .datatablehead td{ padding:3; } Once these styles are added, you can apply them to the control: <ItemStyle cssclass="datatablebody"></ItemStyle> <HeaderStyle font-bold="True" cssclass="datatablehead"></HeaderStyle> Chapter 12 This chapter covers the concepts of user controls and code-behind. The first three exercises for this chapter don't really have any new type code to them; it's only practicing adding user controls to pages 697 Exercise Solutions and switching to using code-behind. The completed code for these pages is available for download from the Wrox website. Exercise 1 Add the header control and navigation bar control to each page in the site. Remember to add the following code at the top of each page: <%@ Register TagPrefix="WroxUnited" TagName="Header" Src="Header.ascx" %> <%@ Register TagPrefix="WroxUnited" TagName="NavBar" Src="NavBar.ascx" %> Solution Refer 57084_Ch12_Ans01.aspx for the code for this question. Exercise 2 Move the C# code for each page (visible in the Code view in Web Matrix) into an associated code-behind file, making sure each control has a corresponding declaration in the code-behind file. Solution See 57084_Ch12_Ans02.aspx for the solution. Exercise 3 Move the C# code from the navbar.ascx control (containing an event-handler) into an associated .cs code-behind file, following the same technique as you used for the other pages on the site. Exercise 4 Create a user control for the Merchandise.aspx page that enables you to easily add new items to the list. You will need to copy a row of the table from Merchandise.aspx into a new ASCX user control file. Make the properties on the image and button controls generic and add some public properties to programmatically set the values on each Web control in the user control. Firstly, here's some code (currently in Merchandise.aspx) that could be placed in the control: <tr> <td> <asp:Image id="imgCap" runat="server" Height="100px" ImageUrl="images/shirt.gif" Width="100px"></asp:Image> </td> <td> The Wrox United shirt, available in one size only</td> <td> <asp:Button id="btnBuyShirt" onclick="AddItemToBasket" runat="server" Width="100px" CommandArgument="Shirt" Text="Buy a shirt!"></asp:Button> 698 Appendix A </td> </tr> If you change the ImageUrl of the image, the Text of the button, and the CommandArgument to empty strings "", then you can set those in the Page_Load() event. Consider the earlier example – the word "Shirt" features in all three of these attributes, so you could add a property like the following to store the name of the item (in this case, shirt), then use this value to construct the appropriate values for these attributes: private string _itemName = ""; public string ItemName { get{ return _itemName; } set{ _itemName = value; } } Here's an example of using this property to update another private variable. This could be used, for example, to provide a default image name: : if (_imageName == "") { _imageName = _itemName + ".jpg"; } You would also need to move the AddItemToBasket() function to the control because the buttons now reside within this control. Since the name of the session is globally available, it's possible to set or update session values from the control just as easily as from a page. You will need three properties in all. The first, ItemName is shown above. You can include an optional ImageName property to override the default value (in case you want to use a .gif, for example). Finally, you need to store the text that describes the item in a Text property and include the value stored in this property in the page using the following syntax: <td><%=Text%></td> All that remains then is to add the item to the page: <WroxUnited:Product id="Shirt" runat="server" ItemName="Shirt" ImageName="shirt.gif" Text="The Wrox United shirt, available in one size only"/> Solution Firstly, the HTML of the Product.ascx user control: <tr> <td> 699 Exercise Solutions <asp:Image id="image1" Width="120px" ImageUrl="<%=imageLink%>" Height="120px" runat="server"></asp:Image> </td> <td> <%=Text%></td> <td> <asp:Button id="button1" onclick="AddItemToBasket" Width="100px" runat="server" Text="<%=buttonText%>" CommandArgument="<%=ItemName%>"></asp:Button> </td> </tr> Next, the code for the Product.ascx user control: using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Caching; using System.Collections; using System.Configuration; namespace WroxUnited { public class Product : UserControl { public Image image1; public Button button1; private string _itemName = ""; public string ItemName { get{ return _itemName; } set{ _itemName = value; } } private string _imageName = ""; public string ImageName { get { return _imageName; } set { _imageName = value; } } private string _text = ""; public string Text { get { return _text; } set { _text = value; } } public void Page_Load() { 700 Appendix A if (_imageName == "") { _imageName = _itemName + ".jpg"; } string imageLink = "images/" + _imageName; string buttonText = "Buy the " + _itemName + "!"; image1.ImageUrl = imageLink; button1.Text = buttonText; } public void AddItemToBasket(object sender, EventArgs e) { System.Collections.Hashtable basketTable = (Hashtable)Session["Basket"]; if (basketTable[_itemName] == null) { basketTable[_itemName] = 0; } int itemCount = (int)basketTable[_itemName]; basketTable[_itemName] = itemCount + 1; } } } In Merchandise.aspx add the following: <%@ Register TagPrefix="WroxUnited" TagName="Product" Src="Product.ascx" %> <table width="600"> <WroxUnited:Product id="Shirt" runat="server" ItemName="Shirt" ImageName="shirt.gif" Text="The Wrox United shirt, available in one size only"/> <WroxUnited:Product id="Hat" runat="Server" ItemName="Hat" ImageName="hat.jpg" Text="The official Wrox United hat!"/> <WroxUnited:Product id="Mascot" runat="Server" ItemName="Mascot" ImageName="mascot1.jpg" Text="The Wrox United cuddly mascot - a must-have for the younger supporters!"/> <WroxUnited:Product id="Plate" runat="server" ItemName="Plate" ImageName="team_s_b.gif" Text="This is a strange square collector's plate of the team!"/> </table> 701 Exercise Solutions [...]... by ASP.NET? 708 Exercise Solutions Solution When a page has errors that are caught during compilation by a NET Framework compiler (remember that ASP.NET pages are compiled), ASP.NET generates a syntax error report with information about the error and sends this information to the browser When an error occurs while a page is being executed, it gives rise to a parser error The difference is that ASP.NET. .. create different add-ins Overall, ASP.NET Web Matrix is a fine choice for a beginner When you want to work faster and on larger projects, you can upgrade to Visual Studio NET 726 Web Matrix Quick Start Starting ASP.NET Web Matrix First download and install ASP.NET Web Matrix as described in Chapter 1 If it is already running, then exit the software Before starting ASP.NET Web Matrix, create your BegASPNET11... charge for getting or using ASP.NET Web Matrix Many add-ins and changes for this product are expected in the next few years For this book, we selected ASP.NET Web Matrix as our editor for the following reasons: ❑ It is free, an important factor for many students starting in ASP.NET ❑ It is small and simple, making it easy to download and install ❑ Its interface is very similar to Visual Studio NET, which... may need to use in the future Although the best things in life are free, that is not necessarily the case with development tools There are some serious limitations to ASP.NET Web Matrix, particularly if you have used a more advanced tool such as Visual Studio or Visual Studio NET: ❑ IntelliSense, a Visual Studio tool that uses pop-ups to help in function and statement completion, is missing in Web Matrix... software as described in Chapter 1 This appendix will cover: ❑ ASP.NET Web Matrix and its uses ❑ Starting Web Matrix ❑ The screen ❑ Entering code ❑ Saving and viewing pages ❑ Reusing code ❑ Class browser What Is Web Matrix? Web Matrix is a development environment This basically means it helps you to write new software (in this case, the ASP.NET pages) Web Matrix helps application development by providing:... return the first occurrence in the DataReader as our string Exercise 6 Create an ASP.NET page containing a drop-down ListBox in which a user can select names of Northwind employees to return their addresses 717 Appendix A Solution private void RetrieveAddress(System.Object sender, System.EventArgs... the same, especially the selection of Template = General, and in the top right graphical selector keep the choice of an ASP.NET page Click OK to create the page You will see a window with the title NewFile.aspx Double-click on the title bar to maximize the window The Screen Let's start with a quick tour of the areas on the screen The Web Matrix screen looks similar to Figure B-1: Figure B-1 727 ... decryptionKey="AutoGenerate" validation="SHA1"/> 723 B Web Matrix Quick Start To write ASP.NET pages, you can choose from several software tools They range from the simple Notepad to the powerful and expensive (Visual Studio NET) In this book, we use a tool called Web Matrix, because it is easy to learn, powerful enough, and most importantly, free... as described in Chapter 1 If it is already running, then exit the software Before starting ASP.NET Web Matrix, create your BegASPNET11 folder as described in Chapter 1 Within that folder, create a MatrixPractice folder and then start ASP.NET Web Matrix After it loads, you get a wizard to create a new document For now, change the location to the nascent MatrixPractice folder and then change the filename...Appendix A Exercise 5 Move the new code in Product.ascx into a code-behind file Chapter 13 This chapter covered how to compile a NET assembly and use it from within our ASP.NET page It also discussed the encapsulation of business logic into a reusable component Exercise 1 Build a data access component that connects to the Travel.mdb access database and retrieves data . control: <tr> <td> 699 Exercise Solutions < ;asp: Image id="image1" Width=" ;12 0px" ImageUrl="<%=imageLink%>" Height=" ;12 0px" runat="server">< /asp: Image> </td> <td> <%=Text%></td> <td> < ;asp: Button. int.Parse(cell.Text); Chapter 11 This chapter deals with tracking users across pages and looks at the ASP. NET objects that are used to enable this feature. Exercise 1 Add some text, Current Topic,. team!"/> </table> 7 01 Exercise Solutions Exercise 5 Move the new code in Product.ascx into a code-behind file. Chapter 13 This chapter covered how to compile a .NET assembly and use it from within our ASP. NET

Ngày đăng: 13/08/2014, 04:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan