ASP.NET 2.0 Everyday Apps For Dumies 2006 phần 7 doc

49 239 0
ASP.NET 2.0 Everyday Apps For Dumies 2006 phần 7 doc

Đ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

<asp:contentplaceholder runat=”server” ➝ 3 id=”ContentPlaceHolder1” > </asp:contentplaceholder> </div> </form> </body> </html> Here are the key points of this listing: ➝ 1 The Master directive indicates that the file is a Master Page. ➝ 2 The Image control displays the banner image that appears at the top of each page. ➝ 3 The ContentPlaceHolder control indicates where the content for each page that uses this master will appear. Building the Menu Page The Menu page (Default.aspx) is the default page for the Product Catalog application. It simply displays a pair of links that let the user go to the Category Maintenance page or the Product Maintenance page. Listing 7-3 shows the code for this page. Listing 7-3: The Menu page (Default.aspx) <%@ Page Language=”C#” ➝ 1 MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” Title=”Acme Pirate Supply” %> <asp:Content ID=”Content1” Runat=”Server” ➝ 2 ContentPlaceHolderID=”ContentPlaceHolder1” > <br /> Welcome to the Maintenance Application.<br /> <br /> <asp:LinkButton ID=”LinkButton1” runat=”server” ➝ 3 PostBackUrl=”CatMaint.aspx”> Maintain Categories </asp:LinkButton> <br /><br /> <asp:LinkButton ID=”LinkButton2” runat=”server” ➝ 4 PostBackUrl=”ProdMaint.aspx”> Maintain Products </asp:LinkButton> </asp:Content> 239 Chapter 7: Building a Product Maintenance Application 14_597760 ch07.qxp 1/11/06 9:57 PM Page 239 Here are some of the key points to note about the code for this page: ➝ 1 The Page directive uses the MasterPageFile attribute to spec- ify the name of the Master Page. ➝ 2 The <Content> element provides the content that’s displayed for the page. ➝ 3 The first <LinkButton> element provides a link to the CatMaint. aspx page. The PostBackUrl attribute is used to post to that page when the user clicks the link. ➝ 4 The second <LinkButton> element provides a link that posts back to the ProdMaint.aspx page. Building the Category Maintenance Page The Category Maintenance page (CatMaint.aspx) lets the user update or delete existing categories or create new categories. It uses a GridView control to let the user modify or delete existing categories. In addition, it uses three text boxes that let the user enter data to define a new category. The text boxes are required because the GridView control doesn’t provide a way for users to insert rows. The CatMaint.aspx file Listing 7-4 shows the .aspx code for the Category Maintenance page. You may want to refer back to Figure 7-3 to see how this page looks on-screen. Listing 7-4: The Category Maintenance page (CatMaint.aspx) <%@ Page Language=”C#” ➝ 1 MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”CatMaint.aspx.cs” Inherits=”CatMaint” Title=”Acme Pirate Supply” %> <asp:Content ID=”Content1” Runat=”Server” ➝ 2 ContentPlaceHolderID=”ContentPlaceHolder1” > Category Maintenance<br /> <br /> <asp:GridView ID=”GridView1” runat=”server” ➝ 3 AutoGenerateColumns=”False” DataKeyNames=”catid” DataSourceID=”SqlDataSource1” OnRowDeleted=”GridView1_RowDeleted” OnRowUpdated=”GridView1_RowUpdated”> 240 Part IV: Building Back-End Applications 14_597760 ch07.qxp 1/11/06 9:57 PM Page 240 <Columns> <asp:BoundField DataField=”catid” ➝ 4 HeaderText=”ID” ReadOnly=”True”> <HeaderStyle HorizontalAlign=”Left” /> <ItemStyle Width=”80px” /> </asp:BoundField> <asp:BoundField DataField=”name” ➝ 5 HeaderText=”Name”> <HeaderStyle HorizontalAlign=”Left” /> <ItemStyle Width=”100px” /> </asp:BoundField> <asp:BoundField DataField=”desc” ➝ 6 HeaderText=”Description”> <HeaderStyle HorizontalAlign=”Left” /> <ItemStyle Width=”400px” /> </asp:BoundField> <asp:CommandField ➝ 7 CausesValidation=”False” ShowEditButton=”True” /> <asp:CommandField ➝ 8 CausesValidation=”False” ShowDeleteButton=”True” /> </Columns> </asp:GridView> <asp:SqlDataSource ID=”SqlDataSource1” ➝ 9 runat=”server” ConflictDetection=”CompareAllValues” ConnectionString= “<%$ ConnectionStrings:ConnectionString %>” OldValuesParameterFormatString=”original_{0}” DeleteCommand=”DELETE FROM [Categories] ➝ 10 WHERE [catid] = @original_catid AND [name] = @original_name AND [desc] = @original_desc” InsertCommand=”INSERT INTO [Categories] ➝ 11 ([catid], [name], [desc]) VALUES (@catid, @name, @desc)” SelectCommand=”SELECT [catid], ➝ 12 [name], [desc] FROM [Categories] ORDER BY [catid]” UpdateCommand=”UPDATE [Categories] ➝ 13 SET [name] = @name, [desc] = @desc WHERE [catid] = @original_catid AND [name] = @original_name AND [desc] = @original_desc”> <DeleteParameters> ➝ 14 <asp:Parameter Name=”original_catid” Type=”String” /> <asp:Parameter Name=”original_name” Type=”String” /> <asp:Parameter Name=”original_desc” Type=”String” /> (continued) 241 Chapter 7: Building a Product Maintenance Application 14_597760 ch07.qxp 1/11/06 9:57 PM Page 241 Listing 7-4 (continued) </DeleteParameters> <UpdateParameters> ➝ 15 <asp:Parameter Name=”name” Type=”String” /> <asp:Parameter Name=”desc” Type=”String” /> <asp:Parameter Name=”original_catid” Type=”String” /> <asp:Parameter Name=”original_name” Type=”String” /> <asp:Parameter Name=”original_desc” Type=”String” /> </UpdateParameters> <InsertParameters> ➝ 16 <asp:Parameter Name=”catid” Type=”String” /> <asp:Parameter Name=”name” Type=”String” /> <asp:Parameter Name=”desc” Type=”String” /> </InsertParameters> </asp:SqlDataSource> <br /> <asp:Label ID=”lblMessage” runat=”server” ➝ 17 EnableViewState=”False” ForeColor=”Red” /><br /> Enter the category information below to create a new category:<br /><br /> <asp:Label ID=”Label1” runat=”server” BorderStyle=”None” Width=”80px” Text=”ID:” /> <asp:TextBox ID=”txtID” runat=”server” /> ➝ 18 &nbsp; <asp:RequiredFieldValidator ID=”RequiredFieldValidator1” runat=”server” ControlToValidate=”txtID” ErrorMessage=”Required.” /> <br /> <asp:Label ID=”Label2” runat=”server” BorderStyle=”None” Width=”80px” Text=”Name:” /> <asp:TextBox ID=”txtName” runat=”server” /> ➝ 19 &nbsp; <asp:RequiredFieldValidator ID=”RequiredFieldValidator2” runat=”server” ControlToValidate=”txtName” ErrorMessage=”Required.” /> <br /> 242 Part IV: Building Back-End Applications 14_597760 ch07.qxp 1/11/06 9:57 PM Page 242 <asp:Label ID=”Label3” runat=”server” BorderStyle=”None” Width=”80px” Text=”Description:” /> <asp:TextBox ID=”txtDesc” runat=”server” /> ➝ 20 &nbsp; <asp:RequiredFieldValidator ID=”RequiredFieldValidator3” runat=”server” ControlToValidate=”txtDesc” ErrorMessage=”Required.” /><br /> <br /> <asp:Button ID=”btnAdd” runat=”server” ➝ 21 OnClick=”btnAdd_Click” Text=”Add Category” /><br /><br /> <asp:LinkButton ID=”LinkButton1” ➝ 22 runat=”server” PostBackUrl=”~/Default.aspx” CausesValidation=”false” > Return to Home Page </asp:LinkButton> </asp:Content> Here’s a detailed look at each of the numbered lines in this listing: ➝ 1 The Page directive specifies the Master Page and other informa- tion for the page. To use the Visual Basic version of the code-behind file — shown in Listing 7-6 — you must change the AutoEventWireup attribute to false. ➝ 2 The <Content> element provides the content that’s displayed in the <ContentPlaceHolder> element of the Master Page. ➝ 3 The GridView control displays the rows from the Categories table. It’s bound to the data source named SqlDataSource1, which is defined in line 9. Notice also that it specifies methods to handle the RowDeleted and RowUpdated events. To use the Visual Basic version of the code-behind file for this page, you should remove the OnRowDeleted and OnRowUpdated attributes. ➝ 4 The elements under the <Columns> element define the columns displayed by the GridView control. This one defines the first column in the grid, which displays the category ID. Notice that this column is read-only. That prevents the user from changing the category ID for a category. ➝ 5 The column defined by this <BoundField> element displays the category name. 243 Chapter 7: Building a Product Maintenance Application 14_597760 ch07.qxp 1/11/06 9:57 PM Page 243 ➝ 6 This column displays the category description. ➝ 7 This line defines a command field that displays an Edit link, which the user can click to edit the row. When the user clicks the Edit link, the labels in the name and desc columns for the row are replaced by text boxes, and the Edit link is replaced by Update and Cancel links. ➝ 8 This line defines a command field that displays a Delete link, which lets the user delete a row. ➝ 9 This <SqlDataSource> element defines the data source used for the GridView control. The ConflictDetection attribute specifies CompareAllValues, which enables optimistic concur- rency checking for the data source. Then the ConnectionString attribute specifies that the connection string for the data source should be retrieved from the Web.config file. Finally, the OldParameterValuesFormatString attribute specifies the format string that’s used to create the parameter names used to supply the original parameter values. In this case, the word original_ is simply added to the beginning of each para- meter name. ➝ 10 The <DeleteCommand> element provides the DELETE statement used to delete rows from the table. Notice that the original values of the catid, name, and desc columns are listed in the WHERE clause. The values @original_catid, @original_name, and @original_desc parameters are automatically provided by the GridView control when the user deletes a row. ➝ 11 The InsertCommand attribute provides the INSERT statement used to insert a row in the Categories table. Note that the GridView control doesn’t use this INSERT statement, as the GridView control doesn’t provide a way for the user to insert rows. Instead, the code that’s executed when the user clicks the Add Category button (defined in line 21) calls this statement. ➝ 12 This SELECT statement is used to retrieve the categories from the Categories table. ➝ 13 The UPDATE statement updates a row in the Categories table. Notice that the original values are used in the WHERE clause to provide optimistic concurrency checking. ➝ 14 The <DeleteParameters> element defines the parameters used by the DELETE statement. ➝ 15 The <UpdateParameters> element defines the parameters used by the UPDATE statement. ➝ 16 The <InsertParameters> element defines the parameters used by the INSERT statement. 244 Part IV: Building Back-End Applications 14_597760 ch07.qxp 1/11/06 9:57 PM Page 244 ➝ 17 This label is used by the code-behind file to display messages. For example, if an error occurs while trying to update or delete a category, a suitable error message is displayed in this label. ➝ 18 This text box lets the user enter the category ID for a new cate- gory. Note that a RequiredFieldValidator ensures that the user enters a value into this field. ➝ 19 This text box lets the user enter the name for a new category. A RequiredFieldValidator is used to force the user to enter a name. ➝ 20 This text box is where the user enters the description for a new category. Once again, a RequiredFieldValidator is present to require an entry for this text box. ➝ 21 The Add Category button lets the user add a new category using the ID, name, and description entered into the text boxes. If you’re using the Visual Basic version of the code-behind file, you should remove the OnClick attribute. ➝ 22 This link button provides a link back to the menu page. Note that CausesValidation is set to false for this button. That way the RequiredFieldValidator isn’t enforced for any of the three text boxes when the user clicks the link. The code-behind file for the Catalog Maintenance page The CatMaint.aspx page requires a code-behind file to handle the button- click event for the Add Category button, as well as the RowUpdated and RowDeleted events for the GridView control. Listing 7-5 shows the C# ver- sion of this code-behind file, and Listing 7-6 shows the Visual Basic version. Listing 7-5: The code-behind file for the Catalog Maintenance page (C#) using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; (continued) 245 Chapter 7: Building a Product Maintenance Application 14_597760 ch07.qxp 1/11/06 9:57 PM Page 245 Listing 7-5 (continued) public partial class CatMaint : System.Web.UI.Page { protected void btnAdd_Click( ➝ 1 object sender, EventArgs e) { setParameter(“catid”, txtID.Text); setParameter(“name”, txtName.Text); setParameter(“desc”, txtDesc.Text); try { SqlDataSource1.Insert(); txtID.Text = “”; txtName.Text = “”; txtDesc.Text = “”; } catch (Exception) { lblMessage.Text = “There is already a category “ + “with that ID. Please try another.”; } } private void setParameter(string name, ➝ 2 string value) { SqlDataSource1.InsertParameters[name] .DefaultValue = value; } protected void GridView1_RowUpdated( ➝ 3 object sender, GridViewUpdatedEventArgs e) { if (e.Exception != null) { lblMessage.Text = “Incorrect data. “ + “Please try again.”; e.ExceptionHandled = true; e.KeepInEditMode = true; } else if (e.AffectedRows == 0) { lblMessage.Text = “That category could not “ + “be updated. Please try again.”; } } protected void GridView1_RowDeleted( ➝ 4 object sender, GridViewDeletedEventArgs e) 246 Part IV: Building Back-End Applications 14_597760 ch07.qxp 1/11/06 9:57 PM Page 246 { if (e.Exception != null) { lblMessage.Text = “That category could not “ + “be deleted.”; e.ExceptionHandled = true; } else if (e.AffectedRows == 0) { lblMessage.Text = “That category could not “ + “be deleted. Please try again.”; } } } Here’s a list that offers a description for every method in this code-behind file: ➝ 1 The btnAdd_Click method is called when the user clicks the Add Category button to add a new row to the Categories table. The method begins by calling a helper method (named setParameter, shown in line 2) to set the value of the catid, name, and desc para- meters, and then calls the Insert method of the data source to execute the INSERT statement. Assuming the INSERT statement is successful, it then clears the three text input fields. However, if the INSERT statement fails, an exception will be thrown. Then the assignment in the catch statement displays an appropriate error message. ➝ 2 The setParameter method provides a simple shorthand for setting the value of one of the data source’s Insert parameters. To set a parameter value, you use the parameter name as an index for the InsertParameters property of the data source, then use the DefaultValue property to set the value. Because this is a bit cumbersome, I created this helper method to make it easier to set a parameter value. ➝ 3 The GridView1_RowUpdated method is called whenever a row of the GridView control has been updated — regardless of whether the update was successful. You can use two properties of the e argument to determine whether the update was successful. If the update results in an exception (as when the database is unavail- able), the Exception property refers to an Exception object; otherwise the Exception property is null. And if the UPDATE statement did not actually update any data, the AffectedRows property will be zero. As you can see, this method tests both prop- erties, displaying an appropriate message in the lblMessage label if an error has occurred. ➝ 4 The GridView1_RowDeleted method is similar to the GridView1_RowUpdated method. It also tests the Exception and AffectedRows properties of the e parameter to see whether an error has occurred. 247 Chapter 7: Building a Product Maintenance Application 14_597760 ch07.qxp 1/11/06 9:57 PM Page 247 Listing 7-6: The code-behind file for the Catalog Maintenance page (VB) Partial Class CatMaint Inherits System.Web.UI.Page Protected Sub btnAdd_Click( _ ➝ 1 ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles btnAdd.Click setParameter(“catid”, txtID.Text) setParameter(“name”, txtName.Text) setParameter(“desc”, txtDesc.Text) Try SqlDataSource1.Insert() txtID.Text = “” txtName.Text = “” txtDesc.Text = “” Catch ex As Exception lblMessage.Text = “There is already a “ _ + “category with that ID. “ _ + “Please try another.” End Try End Sub Private Sub setParameter( _ ➝ 2 ByVal name As String, _ ByVal value As String) SqlDataSource1.InsertParameters(name) _ .DefaultValue = value End Sub Protected Sub GridView1_RowUpdated( _ ➝ 3 ByVal sender As Object, _ ByVal e As System.Web.UI.WebControls. _ GridViewUpdatedEventArgs) _ Handles GridView1.RowUpdated If Not e.Exception Is Nothing Then lblMessage.Text = “Incorrect data. “ _ + “Please try again.” e.ExceptionHandled = True e.KeepInEditMode = True ElseIf e.AffectedRows = 0 Then lblMessage.Text = “That category could not “ _ + “be updated. Please try again.” End If End Sub Protected Sub GridView1_RowDeleted( _ ➝ 4 ByVal sender As Object, _ ByVal e As System.Web.UI. _ WebControls.GridViewDeletedEventArgs) _ Handles GridView1.RowDeleted 248 Part IV: Building Back-End Applications 14_597760 ch07.qxp 1/11/06 9:57 PM Page 248 [...]... product, and a FormView control to display the information for the selected product The FormView control also lets the user edit, delete, or insert product data The following sections present the aspx code that defines this page as well as the code-behind file that handles events raised by the page The ProdMaint.aspx file Listing 7- 7 (drum roll, please) shows the complete aspx code for the Product... control so the user must enter a name for the product ➝ 27 This text box is bound to the shorttext field A RequiredFieldValidator control requires the user to enter a value for this field ➝ 28 The text box for the longtext field is also followed by a RequiredFieldValidator ➝ 29 The text box for the price field does not use a format string to apply the currency format to the price That’s to avoid the... InsertItemTemplate template is displayed when the FormView control is placed in Insert mode The controls defined for this template are the same ones defined for the EditItemTemplate template ➝ 35 This SqlDataSource control, named SqlDataSource2, provides the data for the FormView control The OnDeleted, OnUpdated, and OnInserted attributes specify the methods Chapter 7: Building a Product Maintenance Application... Chapter 7: Building a Product Maintenance Application The code-behind file for the Product Maintenance page Like the CatMaint.aspx page, the ProdMaint.aspx page requires a codebehind file The C# version of this code-behind file is shown in Listing 7- 8, and Listing 7- 9 shows the Visual Basic version Listing 7- 8: using using using using using using using using using using The code-behind file for the... be twoway — that is, for input as well as for output A template can include a link that specifies a command name via the CommandName attribute Then when the user clicks the link, the specified command will be sent to the FormView control The following commands are allowed: ߜ Edit: Places the FormView control in Edit mode and displays the EditItemTemplate template ߜ New: Places the FormView control in... InsertItemTemplate templates of the FormView1 control ➝ 45 A label control named lblMessage appears beneath the FormView control This label displays messages about the success or failure of database updates ➝ 46 Finally, a link button provides a convenient way for the user to get back to the menu page 263 264 Part IV: Building Back-End Applications The FormView Control The new FormView control is similar to... fields Table 8-3 The OrderItems Table Column name Type Description ordernum INT The order number for the order this item is associated with productid VARCHAR(10) The ID for the product represented by this item Note that this column along with the ordernum columns comprise the primary key for this table 273 274 Part IV: Building Back-End Applications Table 8-3 (continued) Column name Type Description name... is the EmptyDataTemplate — used when the data source has no data — in which case, the FormView control displays this instruction: Please select a product In addition, a link lets the user place the FormView control in Insert mode by specifying New for the CommandName attribute ➝ 11 The ItemTemplate displays the data for the row selected by the data source This template consists of several labels and... provided by the TextBox control.) Chapter 7: Building a Product Maintenance Application ➝ 12 The first text box in the item template displays the product ID Note how an ASP.NET 2.0 binding expression is used to bind the Text property of the text box to the productid field of the data source The new Eval method provides a simple way to provide one-way binding for display-only fields ➝ 13 The next TextBox... MultiLine attribute is specified for the text box so the user can enter more than one line of text ➝ 16 This text box displays the longtext field — again, using the MultiLine attribute so the user can enter more than one line of text ➝ 17 This text box binds to the price field of the data source In this case, a format string is used along with the Bind method to apply currency formatting to the price ➝ 18 . Application 14_5 977 60 ch 07. qxp 1/11 /06 9: 57 PM Page 24 9 Listing 7- 7 (continued) <table border= 0 width= 7 50 > ➝ 3 <tr> <td valign=”top” width=” 300 ”> < ;asp: GridView ID=”GridView1”. whether an error has occurred. 24 7 Chapter 7: Building a Product Maintenance Application 14_5 977 60 ch 07. qxp 1/11 /06 9: 57 PM Page 24 7 Listing 7- 6: The code-behind file for the Catalog Maintenance. ID=”RequiredFieldValidator2” runat=”server” ControlToValidate=”txtName” ErrorMessage=”Required.” /> <br /> 24 2 Part IV: Building Back-End Applications 14_5 977 60 ch 07. qxp 1/11 /06 9: 57 PM Page 24 2 < ;asp: Label

Ngày đăng: 05/08/2014, 10:20

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