Upload
smitanair143
View
66
Download
2
Tags:
Embed Size (px)
DESCRIPTION
asp.net
Citation preview
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 1
Chapter 15
How to use the DetailsView and
FormView controls
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 2
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.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 3
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.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 4
A DetailsView control that displays data for a selected product
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 5
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:" />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 6
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 7
Three modes of the DetailsView control
Mode Description
ReadOnly Used to display an item from the data source.
Edit Used to edit an item in the data source.
Insert Used to insert a new item into the data source.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 8
DetailsView control attributes
Attribute Description
ID The ID of this control.
Runat Must specify "server".
DataSourceID The ID of the data source to bind the DetailsView control to.
DataKeyNames A list of field names that form the primary key for the data source.
AutoGenerateRows 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.
DefaultMode Sets the initial mode of the DetailsView control. Valid options are Edit, Insert, or ReadOnly.
AllowPaging Set to True to allow paging.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 9
DetailsView child elements Fields
RowStyle
AlternatingRowStyle
EditRowStyle
InsertRowStyle
CommandRowStyle
EmptyDataRowStyle
EmptyDataTemplate
HeaderStyle
HeaderTemplate
FooterStyle
FooterTemplate
PagerSettings
PagerStyle
PagerTemplate
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 10
Fields child elements
Element Description
asp: BoundField A field bound to a data source column.
asp: ButtonField A field that displays a button.
asp: CheckBoxField A field that displays a check box.
asp: CommandField A field that contains command buttons.
asp: HyperlinkField A field that displays a hyperlink.
asp: ImageField A field that displays an image.
asp: TemplateField A column with custom content.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 11
A DetailsView control that allows paging
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 12
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: " />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 13
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 14
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 that’s bound to the SelectedValue property of the control that contains the list of data items.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 15
A SqlDataSource control with a parameter that’s 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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 16
A DetailsView control with automatically generated command buttons
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 17
Command buttons
Button Description
Edit Places the DetailsView control in Edit mode.
Delete Deletes the current item and leaves the DetailsView control in ReadOnly mode.
New Places the DetailsView control in Insert mode.
Update Displayed only in Edit mode. Updates the data source, then returns to ReadOnly mode.
Insert Displayed only in Insert mode. Inserts the data, then returns to ReadOnly mode.
Cancel Displayed in Edit or Insert mode. Cancels the operation and returns to ReadOnly mode.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 18
Attributes that generate command buttons
Attribute Description
AutoGenerateDeleteButton Generates a Delete button.
AutoGenerateEditButton Generates an Edit button.
AutoGenerateInsertButton 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">
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 19
The Add Field dialog box for adding a command field
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 20
Code generated by the Add Field dialog box <asp:CommandField ButtonType="Button" ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 21
Events raised by the DetailsView control ItemCommand
ItemCreated
DataBound
ItemDeleted
ItemDeleting
ItemEditing
ItemUpdated
ItemUpdating
PageIndexChanged
PageIndexChanging
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 22
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(); }
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 23
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
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 24
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
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 25
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 doesn’t work properly for database columns that allow nulls because two nulls aren’t 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.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 26
A DetailsView control in Edit mode without and with templates
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 27
DetailsView template elements
Element The template used for…
ItemTemplate An individual field
AlternatingItemTemplate Alternating fields
EditItemTemplate A field in Edit mode
InsertItemTemplate A field in Insert mode
HeaderTemplate The header text for a field
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 28
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 29
The Product Maintenance application
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 30
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 31
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">
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 32
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 33
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 34
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 35
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" />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 36
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 37
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> . .
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 38
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 39
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> . .
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 40
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 41
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)"
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 42
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"
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 43
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)"
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 44
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">
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 45
The Default.aspx file (cont.) <SelectParameters> <asp:ControlParameter ControlID="GridView1" Name="ProductID" PropertyName="SelectedValue" Type="String" /> </SelectParameters>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 46
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 47
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" />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 48
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 49
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 50
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 51
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(); }
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 52
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(); }
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 53
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); } }
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 54
A FormView control after a data source has been assigned
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 55
A FormView control in template-editing mode
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 56
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.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 57
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 />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 58
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 59
A generated EditItem template as displayed in a browser window
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 60
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.
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 61
The aspx code for the EditItem template (cont.) <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update"> </asp:LinkButton> <asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"> </asp:LinkButton> </EditItemTemplate>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 62
The Order page as viewed in the Web Forms Designer
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 63
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 64
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 />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 65
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>
Murach’s 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="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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 67
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>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 68
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 />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 69
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 />
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 70
The Order.aspx file (cont.) <asp:Button ID="btnAdd" runat="server" Text="Add to Cart" OnClick="btnAdd_Click" /> <asp:Button ID="Button1" runat="server" Text="Go to Cart" CausesValidation="False" PostBackUrl="~/Cart.aspx" /> </div> </form> </body> </html>
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 71
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"); } }
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 72
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; }
Murach’s ASP.NET 3.5/C#, C15 © 2008, Mike Murach & Associates, Inc. Slide 73
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"]; } }