Вы находитесь на странице: 1из 73

Chapter 15

How to use the DetailsView and FormView controls

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 1

Objectives
Applied Use a DetailsView control to display the data in a single row of a data source. Use a DetailsView control to edit, delete, and insert rows in a data source. Use templates to control the appearance of the fields in a DetailsView control. Use a FormView control to display the data in a single row of a data source. Use a FormView control to edit, delete, and insert rows in a data source.

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 2

Objectives (cont.)
Knowledge Describe the three modes of the DetailsView control. Describe the basic functions of the DetailsView and FormView controls. Explain what the before-action and after-action events of a DetailsView control are typically used for. Explain what the optimistic concurrency bug is and how you can fix it. Describe the templates that you can use to control the appearance of a DetailsView control. Describe how the DetailsView and FormView controls differ. Describe the templates that are generated for a FormView control. Explain what a Master/Detail page is and how you develop one using a DetailsView or FormView control.
Murachs ASP.NET 3.5/C#, C15 2008, Mike Murach & Associates, Inc. Slide 3

A DetailsView control that displays data for a selected product

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 4

The aspx code for the DetailsView control


<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource2" Width="450px"> <Fields> <asp:BoundField DataField="ProductID" HeaderText="Product ID:" ReadOnly="True"> <HeaderStyle Width="125 px" /> <ItemStyle Width="325px" /> </asp:BoundField> <asp:BoundField DataField="Name" HeaderText="Name:" /> <asp:BoundField DataField="ShortDescription" HeaderText="Short Description:" /> <asp:BoundField DataField="LongDescription" HeaderText="Long Description:"/> <asp:BoundField DataField="CategoryID" HeaderText="Category ID:" /> <asp:BoundField DataField="ImageFile" HeaderText="Image File:" />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 5

The aspx code for the DetailsView control (cont.)


<asp:BoundField DataField="UnitPrice" HeaderText="Unit Price:" /> <asp:BoundField DataField="OnHand" HeaderText="On Hand:" /> </Fields> </asp:DetailsView>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 6

Three modes of the DetailsView control


Mode ReadOnly Edit Insert Description Used to display an item from the data source. Used to edit an item in the data source. Used to insert a new item into the data source.

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 7

DetailsView control attributes


Attribute ID Runat DataSourceID DataKeyNames AutoGenerateRows Description The ID of this control. Must specify "server". The ID of the data source to bind the DetailsView control to. A list of field names that form the primary key for the data source. If True, a row is automatically generated for each field in the data source. If False, you must define the rows in the Fields element. Sets the initial mode of the DetailsView control. Valid options are Edit, Insert, or ReadOnly. Set to True to allow paging.

DefaultMode AllowPaging

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 8

DetailsView child elements


Fields RowStyle AlternatingRowStyle EditRowStyle InsertRowStyle CommandRowStyle EmptyDataRowStyle EmptyDataTemplate HeaderStyle HeaderTemplate FooterStyle FooterTemplate PagerSettings PagerStyle PagerTemplate

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 9

Fields child elements


Element asp: BoundField asp: ButtonField asp: CheckBoxField asp: CommandField asp: HyperlinkField asp: ImageField asp: TemplateField Description A field bound to a data source column. A field that displays a button. A field that displays a check box. A field that contains command buttons. A field that displays a hyperlink. A field that displays an image. A column with custom content.

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 10

A DetailsView control that allows paging

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 11

The aspx code for the DetailsView control


<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" Width="450px" AllowPaging="True"> <PagerSettings Mode="NextPreviousFirstLast" /> <Fields> <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True"> <HeaderStyle Width="125px" /> <ItemStyle Width="325px" /> </asp:BoundField> <asp:BoundField DataField="Name" HeaderText="Name:" /> <asp:BoundField DataField="ShortDescription" HeaderText="Short Description:" /> <asp:BoundField DataField="LongDescription" HeaderText="Long Description:" /> <asp:BoundField DataField="CategoryID" HeaderText="Category ID: " />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 12

The aspx code for the DetailsView control (cont.)


<asp:BoundField DataField="ImageFile" HeaderText="Image File:" /> <asp:BoundField DataField="UnitPrice" HeaderText="Unit Price:" /> <asp:BoundField DataField="OnHand" HeaderText="On Hand:" /> </Fields> </asp:DetailsView>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 13

A Master/Detail page typically contains:


A control that lets the user choose an item to display, such as a drop-down list or a GridView control. A data source that retrieves all of the items to be displayed in the list. The control that contains the list of data items should be bound to this data source. A DetailsView control that displays data for the item selected by the user. A data source that retrieves the data for the item selected by the user. The DetailsView control should be bound to this data source. To retrieve the selected item, this data source can use a parameter thats bound to the SelectedValue property of the control that contains the list of data items.

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 14

A SqlDataSource control with a parameter thats bound to a drop-down list


<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString ="<%$ ConnectionStrings:HalloweenConnectionString %>" SelectCommand="SELECT [ProductID], [Name], [ShortDescription], [LongDescription], [CategoryID], [ImageFile], [UnitPrice], [OnHand] FROM [Products] WHERE ([ProductID] = @ProductID)"> <SelectParameters> <asp:ControlParameter ControlID="ddlProducts" Name="ProductID" PropertyName="SelectedValue" Type="String" /> </SelectParameters> </asp:SqlDataSource>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 15

A DetailsView control with automatically generated command buttons

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 16

Command buttons
Button Edit Delete New Update Insert Cancel Description Places the DetailsView control in Edit mode. Deletes the current item and leaves the DetailsView control in ReadOnly mode. Places the DetailsView control in Insert mode. Displayed only in Edit mode. Updates the data source, then returns to ReadOnly mode. Displayed only in Insert mode. Inserts the data, then returns to ReadOnly mode. Displayed in Edit or Insert mode. Cancels the operation and returns to ReadOnly mode.

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 17

Attributes that generate command buttons


Attribute AutoGenerateDeleteButton AutoGenerateEditButton AutoGenerateInsertButton Description Generates a Delete button. Generates an Edit button. Generates a New button.

A DetailsView element that automatically generates command buttons


<asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="SqlDataSource2" DataKeyNames="ProductID" AutoGenerateRows="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateInsertButton="True">

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 18

The Add Field dialog box for adding a command field

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 19

Code generated by the Add Field dialog box


<asp:CommandField ButtonType="Button" ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 20

Events raised by the DetailsView control


ItemCommand ItemCreated DataBound ItemDeleted ItemDeleting ItemEditing ItemUpdated ItemUpdating PageIndexChanged PageIndexChanging

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 21

An event handler for the ItemUpdated event


protected void DetailsView1_ItemUpdated( object sender, DetailsViewUpdatedEventArgs e) { if (e.Exception != null) { lblError.Text = "A database error has occurred.<br /><br />" + "Message: " + e.Exception.Message; e.ExceptionHandled = true; e.KeepInEditMode = true; } else if (e.AffectedRows == 0) lblError.Text = "Another user may have updated that product." + "<br>Please try again."; else GridView1.DataBind(); }

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 22

A generated Delete statement that handles concurrency errors


DELETE FROM [Products] WHERE [ProductID] = @original_ProductID AND [Name] = @original_Name AND [ShortDescription] = @original_ShortDescription AND [LongDescription] = @original_LongDescription AND [CategoryID] = @original_CategoryID AND [ImageFile] = @original_ImageFile AND [UnitPrice] = @original_UnitPrice AND [OnHand] = @original_OnHand

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 23

How to modify the Delete statement for a column that allows nulls
DELETE FROM [Products] WHERE [ProductID] = @original_ProductID AND [Name] = @original_Name AND [ShortDescription] = @original_ShortDescription AND [LongDescription] = @original_LongDescription AND [CategoryID] = @original_CategoryID AND ( [ImageFile] = @original_ImageFile OR ImageFile IS NULL AND @original_ImageFile IS NULL ) AND [UnitPrice] = @original_UnitPrice AND [OnHand] = @original_OnHand

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 24

How to fix the optimistic concurrency bug


When you select optimistic concurrency for a data source in the Data Source Configuration Wizard, the wizard adds code to the Update and Delete statements that prevents concurrency errors. Unfortunately, the generated code for Update and Delete statements doesnt work properly for database columns that allow nulls because two nulls arent treated as equal. To fix this error, you can edit the Update and Delete statements so they include an IS NULL test for each column that allows nulls.

Known bug
This is a known bug in the final release of this product.

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 25

A DetailsView control in Edit mode without and with templates

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 26

DetailsView template elements


Element ItemTemplate AlternatingItemTemplate EditItemTemplate InsertItemTemplate HeaderTemplate The template used for An individual field Alternating fields A field in Edit mode A field in Insert mode The header text for a field

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 27

The aspx code for a custom template field


<asp:TemplateField HeaderText="Name:"> <ItemTemplate> <asp:Label ID="Label8" runat="server" Text='<%# Bind("Name") %>'> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' Width="200px" MaxLength="50"> </asp:TextBox> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' Width="200px" MaxLength="50"> </asp:TextBox> </InsertItemTemplate> <HeaderStyle HorizontalAlign="Left" Width="150px" /> <ItemStyle Width="250px" /> </asp:TemplateField>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 28

The Product Maintenance application

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 29

The Default.aspx file: Product Maintenance application


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Chapter 15: Product Maintenance</title> <style type="text/css"> .style1 {width: 300px;} .style2 {width: 400px;} </style> </head>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 30

The Default.aspx file (cont.)


<body> <form id="form1" runat="server"> <div> <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/banner.jpg" /> <br /><br /> <table> <tr> <td class="style1" valign="top"> <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AllowPaging="True" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" SelectedIndex="0" CellPadding="4" GridLines="None" ForeColor="Black">

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 31

The Default.aspx file (cont.)


<Columns> <asp:BoundField DataField="ProductID" HeaderText="ID" ReadOnly="True"> <HeaderStyle HorizontalAlign="Left" /> <ItemStyle Width="75px" /> </asp:BoundField> <asp:BoundField DataField="Name" HeaderText="Name"> <HeaderStyle HorizontalAlign="Left" /> <ItemStyle Width="200px" /> </asp:BoundField> <asp:BoundField DataField="CategoryID" HeaderText="Category" /> <asp:CommandField ButtonType="Button" ShowSelectButton="True" /> </Columns>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 32

The Default.aspx file (cont.)


<HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="White" /> <RowStyle BackColor="White" ForeColor="Black" /> <AlternatingRowStyle BackColor="WhiteSmoke" ForeColor="Black" /> <SelectedRowStyle BackColor="Blue" ForeColor="White" /> <FooterStyle BackColor="Silver" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="Silver" ForeColor="Blue" HorizontalAlign="Center" /> </asp:GridView>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 33

The Default.aspx file (cont.)


<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HalloweenConnectionString %>" SelectCommand="SELECT [ProductID], [Name], [CategoryID] FROM [Products] ORDER BY [ProductID]"> </asp:SqlDataSource> </td>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 34

The Default.aspx file (cont.)


<td class="style2" valign="top"> <asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="SqlDataSource2" DataKeyNames="ProductID" Height="50px" Width="400px" AutoGenerateRows="False" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None" OnItemDeleted="DetailsView1_ItemDeleted" OnItemDeleting="DetailsView1_ItemDeleting" OnItemInserted="DetailsView1_ItemInserted" OnItemUpdated="DetailsView1_ItemUpdated"> <RowStyle BackColor="#DEDFDE" ForeColor="Black" />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 35

The Default.aspx file (cont.)


<Fields> <asp:TemplateField HeaderText="Product ID:"> <ItemTemplate> <asp:Label ID="Label4" runat="server" Text='<%# Bind("ProductID") %>'> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Eval("ProductID") %>'> </asp:Label> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="txtID" runat="server" Text='<%# Bind("ProductID") %>' Width="100px" MaxLength="10"> </asp:TextBox>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 36

The Default.aspx file (cont.)


<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtID" Display="Dynamic" ErrorMessage= "Product ID is a required field." ForeColor="White">* </asp:RequiredFieldValidator> </InsertItemTemplate> <HeaderStyle HorizontalAlign="Left" Width="150px" /> <ItemStyle Width="250px" /> </asp:TemplateField> . .

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 37

The Default.aspx file (cont.)


<asp:TemplateField HeaderText="Category:"> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("CategoryID") %>'> </asp:Label> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="ddlCategory" runat="server" DataSourceID="SqlDataSource3" DataTextField="LongName" DataValueField="CategoryID" SelectedValue= '<%# Bind("CategoryID") %>' Width="130px"> </asp:DropDownList> </EditItemTemplate>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 38

The Default.aspx file (cont.)


<InsertItemTemplate> <asp:DropDownList ID="ddlCategory" runat="server" DataSourceID="SqlDataSource3" DataTextField="LongName" DataValueField="CategoryID" SelectedValue= '<%# Bind("CategoryID") %>' Width="130px"> </asp:DropDownList> </InsertItemTemplate> <HeaderStyle HorizontalAlign="Left" Width="150px" /> <ItemStyle Width="250px" /> </asp:TemplateField> . .

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 39

The Default.aspx file (cont.)


<asp:CommandField ButtonType="Button" ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" /> </Fields> <HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="Black" /> <EditRowStyle BackColor="Blue" Font-Bold="True" ForeColor="White" /> </asp:DetailsView>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 40

The Default.aspx file (cont.)


<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:HalloweenConnectionString %>" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [ProductID], [Name], [ShortDescription], [LongDescription], [CategoryID], [ImageFile], [UnitPrice], [OnHand] FROM [Products] WHERE ([ProductID] = @ProductID)"

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 41

The Default.aspx file (cont.)


DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @original_ProductID AND [Name] = @original_Name AND [ShortDescription] = @original_ShortDescription AND [LongDescription] = @original_LongDescription AND [CategoryID] = @original_CategoryID AND ( [ImageFile] = @original_ImageFile OR ImageFile IS NULL AND @original_ImageFile IS NULL ) AND [UnitPrice] = @original_UnitPrice AND [OnHand] = @original_OnHand"

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 42

The Default.aspx file (cont.)


InsertCommand="INSERT INTO [Products] ([ProductID], [Name], [ShortDescription], [LongDescription], [CategoryID], [ImageFile], [UnitPrice], [OnHand]) VALUES (@ProductID, @Name, @ShortDescription, @LongDescription, @CategoryID, @ImageFile, @UnitPrice, @OnHand)"

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 43

The Default.aspx file (cont.)


UpdateCommand="UPDATE [Products] SET [Name] = @Name, [ShortDescription] = @ShortDescription, [LongDescription] = @LongDescription, [CategoryID] = @CategoryID, [ImageFile] = @ImageFile, [UnitPrice] = @UnitPrice, [OnHand] = @OnHand WHERE [ProductID] = @original_ProductID AND [Name] = @original_Name AND [ShortDescription] = @original_ShortDescription AND [LongDescription] = @original_LongDescription AND [CategoryID] = @original_CategoryID AND ( [ImageFile] = @original_ImageFile OR ImageFile IS NULL AND @original_ImageFile IS NULL ) AND [UnitPrice] = @original_UnitPrice AND [OnHand] = @original_OnHand">

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 44

The Default.aspx file (cont.)


<SelectParameters> <asp:ControlParameter ControlID="GridView1" Name="ProductID" PropertyName="SelectedValue" Type="String" /> </SelectParameters>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 45

The Default.aspx file (cont.)


<DeleteParameters> <asp:Parameter Name="original_ProductID" Type="String" /> <asp:Parameter Name="original_Name" Type="String" /> <asp:Parameter Name="original_ShortDescription" Type="String" /> <asp:Parameter Name="original_LongDescription" Type="String" /> <asp:Parameter Name="original_CategoryID" Type="String" /> <asp:Parameter Name="original_ImageFile" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> <asp:Parameter Name="original_OnHand" Type="Int32" /> </DeleteParameters>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 46

The Default.aspx file (cont.)


<UpdateParameters> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="ShortDescription" Type="String" /> <asp:Parameter Name="LongDescription" Type="String" /> <asp:Parameter Name="CategoryID" Type="String" /> <asp:Parameter Name="ImageFile" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="OnHand" Type="Int32" /> <asp:Parameter Name="original_ProductID" Type="String" /> <asp:Parameter Name="original_Name" Type="String" /> <asp:Parameter Name="original_ShortDescription" Type="String" />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 47

The Default.aspx file (cont.)


<asp:Parameter Name="original_LongDescription" Type="String" /> <asp:Parameter Name="original_CategoryID" Type="String" /> <asp:Parameter Name="original_ImageFile" Type="String" /> <asp:Parameter Name="original_UnitPrice" Type="Decimal" /> <asp:Parameter Name="original_OnHand" Type="Int32" /> </UpdateParameters>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 48

The Default.aspx file (cont.)


<InsertParameters> <asp:Parameter Name="ProductID" Type="String" /> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="ShortDescription" Type="String" /> <asp:Parameter Name="LongDescription" Type="String" /> <asp:Parameter Name="CategoryID" Type="String" /> <asp:Parameter Name="ImageFile" Type="String" /> <asp:Parameter Name="UnitPrice" Type="Decimal" /> <asp:Parameter Name="OnHand" Type="Int32" /> </InsertParameters> </asp:SqlDataSource>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 49

The Default.aspx file (cont.)


<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:HalloweenConnectionString %>" SelectCommand="SELECT [CategoryID], [LongName] FROM [Categories] ORDER BY [LongName]"> </asp:SqlDataSource><br /> <asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText= "Please correct the following errors:" /> <br /> <asp:Label ID = "lblError" runat="server" ForeColor="Red" EnableViewState="False"></asp:Label> </td> </tr> </table> </div> </form> </body></html>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 50

The Default.aspx.cs file: Product Maintenance application


public partial class _Default : System.Web.UI.Page { protected void DetailsView1_ItemUpdated( object sender, DetailsViewUpdatedEventArgs e) { if (e.Exception != null) { lblError.Text = "A database error has occurred.<br /><br />" + "Message: " + e.Exception.Message; e.ExceptionHandled = true; e.KeepInEditMode = true; } else if (e.AffectedRows == 0) lblError.Text = "Another user may have updated that " + " product<br />Please try again."; else GridView1.DataBind(); }
Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 51

The Default.aspx.cs file (cont.)


protected void DetailsView1_ItemDeleted( object sender, DetailsViewDeletedEventArgs e) { if (e.Exception != null) { lblError.Text = "A database error has occurred.<br /><br />" + "Message: " + e.Exception.Message; e.ExceptionHandled = true; } else if (e.AffectedRows == 0) lblError.Text = "Another user may have updated that " + "product.<br />Please try again."; else GridView1.DataBind(); }

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 52

The Default.aspx.cs file (cont.)


protected void DetailsView1_ItemInserted( object sender, DetailsViewInsertedEventArgs e) { if (e.Exception != null) { lblError.Text = "A database error has occurred.<br /><br />" + "Message: " + e.Exception.Message; e.ExceptionHandled = true; e.KeepInInsertMode = true; } else GridView1.DataBind(); } protected void DetailsView1_ItemDeleting( object sender, DetailsViewDeleteEventArgs e) { e.Values["UnitPrice"] = e.Values["UnitPrice"].ToString().Substring(1); } }

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 53

A FormView control after a data source has been assigned

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 54

A FormView control in template-editing mode

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 55

How the FormView control differs from the DetailsView control


The DetailsView control can be easier to work with, but the FormView control provides more formatting and layout options. The DetailsView control can use BoundField elements or TemplateField elements with templates that use data binding expressions to define bound data fields. The FormView control can use only templates with data binding expressions to display bound data. The DetailsView control renders each field as a table row, but the FormView control renders all the fields in a template as a single table row.

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 56

The Item template generated for a FormView control


<asp:FormView ID="FormView1" runat="server" DataKeyNames="ProductID" DataSourceID="SqlDataSource2"> <ItemTemplate> ProductID: <asp:Label ID="ProductIDLabel" runat="server" Text='<%# Eval("ProductID") %>' /><br /> Name: <asp:Label ID="NameLabel" runat="server" Text='<%# Bind("Name") %>' /><br /> ShortDescription: <asp:Label ID="ShortDescriptionLabel" runat="server" Text='<%# Bind("ShortDescription") %>' /><br /> LongDescription: <asp:Label ID="LongDescriptionLabel" runat="server" Text='<%# Bind("LongDescription") %>' /><br /> CategoryID: <asp:Label ID="CategoryIDLabel" runat="server" Text='<%# Bind("CategoryID") %>' /><br />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 57

The Item template (cont.)


ImageFile: <asp:Label ID="ImageFileLabel" runat="server" Text='<%# Bind("ImageFile") %>' /><br /> UnitPrice: <asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Bind("UnitPrice") %>' /><br /> OnHand: <asp:Label ID="OnHandLabel" runat="server" Text='<%# Bind("OnHand") %>' /><br /> </ItemTemplate> . . . </asp:FormView>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 58

A generated EditItem template as displayed in a browser window

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 59

The aspx code for the EditItem template


<EditItemTemplate> ProductID: <asp:Label ID="ProductIDLabel1" runat="server" Text='<%# Eval("ProductID") %>'> </asp:Label><br /> Name: <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>'> </asp:TextBox><br /> ShortDescription: <asp:TextBox ID="ShortDescriptionTextBox" runat="server" Text='<%# Bind("ShortDescription") %>'> </asp:TextBox><br /> . . The code generated for the LongDescription, . CategoryID, ImageFile, UnitPrice, and OnHand . columns is similar to the code generated for the ShortDescription column. . .

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 60

The aspx code for the EditItem template (cont.)


<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update"> </asp:LinkButton>&nbsp; <asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"> </asp:LinkButton> </EditItemTemplate>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 61

The Order page as viewed in the Web Forms Designer

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 62

The Order.aspx file: Shopping Cart application


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Chapter 15: Shopping Cart</title> <style type="text/css"> .style1 {width: 250px;} .style2 {width: 20px;} </style> </head>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 63

The Order.aspx file (cont.)


<body> <form id="form1" runat="server"> <div> <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/banner.jpg" /><br /><br /> <asp:Label ID="Label1" runat="server" Text="Please select a product:"></asp:Label> <asp:DropDownList ID="ddlProducts" runat="server" Width="150px" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="Name" DataValueField="ProductID"> </asp:DropDownList> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HalloweenConnectionString %>" SelectCommand="SELECT [ProductID], [Name] FROM [Products] ORDER BY [Name]"> </asp:SqlDataSource> <br />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 64

The Order.aspx file (cont.)


<asp:FormView ID="FormView1" runat="server" DataSourceID="SqlDataSource2"> <ItemTemplate> <table> <tr> <td class="style1"> <asp:Label ID="lblName" runat="server" style="font-weight: 700; font-size: larger" Text='<%# Bind("Name") %>' > </asp:Label> </td> <td class="style2" rowspan="4" valign="top"></td> <td rowspan="4" valign="top"> <asp:Image ID="imgProduct" runat="server" Height="200px" ImageUrl='<%# Bind("ImageFile", "Images/Products/{0}") %>' /> </td> </tr>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 65

The Order.aspx file (cont.)


<tr> <td class="style1"> <asp:Label ID="lblShortDescription" runat="server" Text= '<%# Bind("ShortDescription") %>'> </asp:Label> </td> </tr> <tr> <td class="style1"> <asp:Label ID="lblLongDescription" runat="server" Text= '<%# Bind("LongDescription") %>'> </asp:Label> </td> </tr>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 66

The Order.aspx file (cont.)


<tr> <td class="style1"> <asp:Label ID="lblUnitPrice" runat="server" style="font-weight: 700; font-size: larger" Text='<%# Bind("UnitPrice", "{0:c} each") %>'> </asp:Label> </td> </tr> </table> </ItemTemplate> </asp:FormView>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 67

The Order.aspx file (cont.)


<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:HalloweenConnectionString %>" SelectCommand="SELECT [ProductID], [Name], [ShortDescription], [LongDescription], [ImageFile], [UnitPrice] FROM [Products] WHERE ([ProductID] = @ProductID)"> <SelectParameters> <asp:ControlParameter ControlID="ddlProducts" Name="ProductID" PropertyName="SelectedValue" Type="String" /> </SelectParameters> </asp:SqlDataSource><br />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 68

The Order.aspx file (cont.)


<asp:Label ID="Label2" runat="server" Text="Quantity:" Width="80px"></asp:Label> <asp:TextBox ID="txtQuantity" runat="server" Width="80px"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtQuantity" Display="Dynamic" ErrorMessage="Quantity is a required field."> </asp:RequiredFieldValidator> <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtQuantity" Display="Dynamic" ErrorMessage= "Quantity must be greater than zero." Operator="GreaterThan" ValueToCompare="0"> </asp:CompareValidator><br /><br />

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 69

The Order.aspx file (cont.)


<asp:Button ID="btnAdd" runat="server" Text="Add to Cart" OnClick="btnAdd_Click" />&nbsp; <asp:Button ID="Button1" runat="server" Text="Go to Cart" CausesValidation="False" PostBackUrl="~/Cart.aspx" /> </div> </form> </body> </html>

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 70

The Order.aspx.cs file: Shopping Cart application


public partial class Order : System.Web.UI.Page { private Product selectedProduct; protected void btnAdd_Click(object sender, EventArgs e) { if (Page.IsValid) { selectedProduct = this.GetSelectedProduct(); CartItem item = new CartItem(); item.Product = selectedProduct; item.Quantity = Convert.ToInt32(txtQuantity.Text); this.AddToCart(item); Response.Redirect("Cart.aspx"); } }

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 71

The Order.aspx.cs file (cont.)


private Product GetSelectedProduct() { DataView productsTable = (DataView) SqlDataSource2.Select( DataSourceSelectArguments.Empty); DataRowView row = (DataRowView) productsTable[0]; Product p = new Product(); p.ProductID = row["ProductID"].ToString(); p.Name = row["Name"].ToString(); p.ShortDescription = row["ShortDescription"].ToString(); p.LongDescription = row["LongDescription"].ToString(); p.UnitPrice = (decimal)row["UnitPrice"]; p.ImageFile = row["ImageFile"].ToString(); return p; }

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 72

The Order.aspx.cs file (cont.)


private void AddToCart(CartItem item) { SortedList cart = this.GetCart(); string productID = selectedProduct.ProductID; if (cart.ContainsKey(productID)) { CartItem existingItem = (CartItem)cart[productID]; existingItem.Quantity += item.Quantity; } else cart.Add(productID, item); } private SortedList GetCart() { if (Session["Cart"] == null) Session.Add("Cart", new SortedList()); return (SortedList) Session["Cart"]; } }

Murachs ASP.NET 3.5/C#, C15

2008, Mike Murach & Associates, Inc.

Slide 73

Вам также может понравиться