Data-Driven - 1 © Minder Chen, Building Data-Driven Web Sites in ASP.NET 2.0
Data-Driven - 2 © Minder Chen, Codeless Data-Binding Process Source:
Data-Driven - 3 © Minder Chen, Data Bound Controls DataGrid DataList GridView DetailsView FormView Repeater New in ASP.NET 2.0
Data-Driven - 4 © Minder Chen, Data-Bound Controls
Data-Driven - 5 © Minder Chen, Data Bound Controls and Data Source Controls
Data-Driven - 6 © Minder Chen, Create a New Data Source Drag and drop the AccessDataSource Web server control on to a Web form. Click the smart tab of the AccessDataSource1 to select common tasks for the AccessDataSource Click on the Configure Data Source… task Smart tag icon Smart tag menu
Data-Driven - 7 © Minder Chen, Select the Access database
Data-Driven - 8 © Minder Chen, Define a SQL (Select) statement SELECT [CategoryID], [CategoryName], [Description] FROM [Categories] Don't choose any query name if you need to create a data source that will be used to insert, update, or delete data in the database.
Data-Driven - 9 © Minder Chen, Test Query
Data-Driven - 10 © Minder Chen, <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]">
Data-Driven - 11 © Minder Chen, CategoryList.aspx
Data-Driven - 12 © Minder Chen, Connecting Data Source and GridView Drop and drop a GridView to the Web form From the GridView smart tag menu, click on the dropdown listbox -- Choose Data Source and then select AccessDataSource1
Data-Driven - 13 © Minder Chen, Edit Columns…
Data-Driven - 14 © Minder Chen, Edit Columns…
Data-Driven - 15 © Minder Chen, Create a HyperLinkField for the CategoryName Column Delete the CategoryName from the Selected Fields list box Highlight HyperlinkField and click Add Move the HyperLinkField to the position between CategoryID and Description in the Selected Fields list box Set up the properties of the HyperlinkField
Data-Driven - 16 © Minder Chen, Set up HyperlinkField Set up the Hyperlink field so that it displays CategoryName as the link words, and links to ProductsByCategory.aspx while passing two QueryString variables cid and cname where cid contains CategoryID and cname contains CategoryName ProductsByCategory.aspx?cid={0}&cname={1} CategoryID, CategoryName CategoryID CategoryName
Data-Driven - 17 © Minder Chen, Source Code <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" DataSourceID="AccessDataSource1"> <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" /> <asp:HyperLinkField DataNavigateUrlFields="CategoryID, CategoryName" DataNavigateUrl FormatString = " ProductsByCategory.aspx?cid={0}&cname={1}" DataTextField="CategoryName" HeaderText="Category Name" /> <asp:BoundField DataField="Description" H HeaderText="Description" SortExpression="Description" />
Data-Driven - 18 © Minder Chen, CategoryList.aspx Untitled Page Category List <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" DataSourceID="AccessDataSource1"> <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" /> <asp:HyperLinkField DataNavigateUrlFields="CategoryID, CategoryName" DataNavigateUrlFormatString="ProductsByCategory.aspx?cid={0}&cname={1}" DataTextField="CategoryName" HeaderText="Category Name" /> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]">
Data-Driven - 19 © Minder Chen, ProductsByCategory.aspx
Data-Driven - 20 © Minder Chen, Choose Data Source Edit Data Source
Data-Driven - 21 © Minder Chen, Define the SQL Statement SELECT [ProductID], [ProductName], [Discontinued], [UnitPrice] FROM [Products] WHERE ([CategoryID] = ?) Make sure you choose Products table
Data-Driven - 22 © Minder Chen, Add Where Clause
Data-Driven - 23 © Minder Chen, Parameterized Commands Parameter properties –Parameterized database commands Example: –Get value for WHERE clause in SelectCommand from QueryString parameter or item selected in a drop-down list Web server control Example: –Get value for WHERE clause in DeleteCommand from GridView
Data-Driven - 24 © Minder Chen, Parameters Properties NameDescription SelectParametersSpecifies parameters for SelectCommand InsertParameters UpdateParameters DeleteParameters FilterParametersSpecifies parameters for FilterExpression Specifies parameters for InsertCommand Specifies parameters for UpdateCommand Specifies parameters for DeleteCommand
Data-Driven - 25 © Minder Chen, Parameter TypesNameDescription ControlParameter Binds a replaceable parameter to a control property CookieParameter Binds a replaceable parameter to a cookie value` FormParameter Binds a replaceable parameter to a form field ProfileParameter Binds a replaceable parameter to a profile property QueryStringParameterBinds a replaceable parameter to a query string parameter Parameter Binds a replaceable parameter to a data field SessionParameter Binds a replaceable parameter to a session variable
Data-Driven - 26 © Minder Chen, Test Query
Data-Driven - 27 © Minder Chen,
Data-Driven - 28 © Minder Chen, AutoFormat
Data-Driven - 29 © Minder Chen, TemplateField
Data-Driven - 30 © Minder Chen, Code for TemplateField '> '>
Data-Driven - 31 © Minder Chen, Edit Template
Data-Driven - 32 © Minder Chen, Edit Template
Data-Driven - 33 © Minder Chen, Set Up Text property
Data-Driven - 34 © Minder Chen, Set up NavigateUrl property ProductRecord.aspx?pid={0}
Data-Driven - 35 © Minder Chen, End Template Editing
Data-Driven - 36 © Minder Chen, ProductsByCategory.aspx Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) LabelCategoryID.Text = Request.QueryString("cid") LabelCategoryName.Text = Request.QueryString("cname") End Sub Products by a Category CategoryID: Catgeory Name:
Data-Driven - 37 © Minder Chen, Continued… <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="AccessDataSource1" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" > <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" /> <asp:TemplateField HeaderText="Product Name" SortExpression="ProductName"> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl=' ' Text=' '> <asp:TextBox ID="TextBox1" runat="server" Text=' '>
Data-Driven - 38 © Minder Chen, Continued… <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" /> <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" DataFormatString="{0:c}" > <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
Data-Driven - 39 © Minder Chen, Continued… <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" SelectCommand="SELECT [ProductID], [ProductName], [Discontinued], [UnitPrice] FROM [Products] WHERE ([CategoryID] = ?)"> <asp:QueryStringParameter DefaultValue="1" Name="CategoryID" QueryStringField="cid" Type="Int32" />
Data-Driven - 40 © Minder Chen, ProductRecord.aspx Runtime
Data-Driven - 41 © Minder Chen, Define the SQL Statement SELECT [ProductID], [ProductName], [CategoryID], [UnitPrice], [UnitsInStock], [Discontinued] FROM [Products] WHERE ([ProductID] = ?)
Data-Driven - 42 © Minder Chen, Add Where Clause
Data-Driven - 43 © Minder Chen, Use DetailsView (One Record at a Time)
Data-Driven - 44 © Minder Chen, Format the DetailsView
Data-Driven - 45 © Minder Chen, ProductRecord.aspx Untitled Page Product Record <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" CellPadding="4" DataKeyNames="ProductID" DataSourceID="AccessDataSource1" Font-Bold="False" ForeColor="#333333" GridLines="None" Height="50px"> <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" /> <asp:BoundField DataField="ProductName" ItemStyle-Width="200px" HeaderText="ProductName" SortExpression="ProductName" /> <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" SortExpression="CategoryID" />
Data-Driven - 46 © Minder Chen, Continued… <asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="UnitPrice" SortExpression="UnitPrice"> <asp:BoundField DataField="UnitsInStock" DataFormatString="{0} in stock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" /> <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" /> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" SelectCommand="SELECT [ProductID], [ProductName], [CategoryID], [UnitPrice], [UnitsInStock], [Discontinued] FROM [Products] WHERE ([ProductID] = ?)"> <asp:QueryStringParameter Name="ProductID" QueryStringField="pid" Type="Int32" />
Data-Driven - 47 © Minder Chen, Manage Categories
Data-Driven - 48 © Minder Chen,
Data-Driven - 49 © Minder Chen, Define the SQL Statement
Data-Driven - 50 © Minder Chen, Use Optimistic Concurrency Control <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = ? AND [CategoryName] = ? AND [Description] = ?" InsertCommand="INSERT INTO [Categories] ([CategoryID], [CategoryName], [Description]) VALUES (?, ?, ?)" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName] = ?, [Description] = ? WHERE [CategoryID] = ? AND [CategoryName] = ? AND [Description] = ?" ConflictDetection="CompareAllValues">
Data-Driven - 51 © Minder Chen, Without Optimistic Concurrency Control <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = ?" InsertCommand="INSERT INTO [Categories] ([CategoryID], [CategoryName], [Description]) VALUES (?, ?, ?)" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName] = ?, [Description] = ? WHERE [CategoryID] = ?">
Data-Driven - 52 © Minder Chen, CategoryUpdateGridView.aspx Untitled Page Manage Categories <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" DataSourceID="AccessDataSource1" AllowPaging="True" PageSize="5" AllowSorting="True" > <asp:CommandField ButtonType="Button" HeaderText="Actions" ShowDeleteButton="True" ShowEditButton="True" /> <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" /> <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
Data-Driven - 53 © Minder Chen, Continued… <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = ? AND [CategoryName] = ? AND [Description] = ?" InsertCommand="INSERT INTO [Categories] ([CategoryID], [CategoryName], [Description]) VALUES (?, ?, ?)" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]" UpdateCommand="UPDATE [Categories] SET [CategoryName] = ?, [Description] = ? WHERE [CategoryID] = ? AND [CategoryName] = ? AND [Description] = ?" ConflictDetection="CompareAllValues">
Data-Driven - 54 © Minder Chen, Change Description Field to Template Field
Data-Driven - 55 © Minder Chen, Choose Edit Template
Data-Driven - 56 © Minder Chen, Change EditItemTemplate
Data-Driven - 57 © Minder Chen, for Description <asp:TemplateField HeaderText="Description" SortExpression="Description"> <asp:Label ID="Label1" runat="server" Text=' '> <asp:TextBox ID="TextBox1" runat="server" Text=' '>
Data-Driven - 58 © Minder Chen, Change TextBox TextMode Property from SingleLine to MultiLine
Data-Driven - 59 © Minder Chen, CategoryUpdateGridView2.aspx
Data-Driven - 60 © Minder Chen, CategoryProductMasterDetail.aspx
Data-Driven - 61 © Minder Chen,
Data-Driven - 62 © Minder Chen, CategoryProductMasterDetail.aspx Protected Sub DropDownList1_SelectedIndexChanged( ByVal sender As Object, ByVal e As System.EventArgs ) LabelCategory.Text = "Category ID selected: " & DropDownList1.SelectedItem.Value LabelCategory.Text &= " Category Name selected: " & DropDownList1.SelectedItem.Text End Sub Untitled Page <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="AccessDataSource1" DataTextField="CategoryName" DataValueField="CategoryID" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]">
Data-Driven - 63 © Minder Chen, CatgeoryProductMasterDetail2.aspx
Data-Driven - 64 © Minder Chen,
Data-Driven - 65 © Minder Chen,
Data-Driven - 66 © Minder Chen, CategoryProductMasterDetail3.aspx
Data-Driven - 67 © Minder Chen, CategoryProductMasterDetail3.aspx Untitled Page <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="AccessDataSource1" DataTextField="CategoryName" DataValueField="CategoryID"AppendDataBoundItems=true> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~~/App_Data/northwind.mdb" SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]" CancelSelectOnNullParameter=false>
Data-Driven - 68 © Minder Chen, Continued… <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="AccessDataSource2"> <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" /> <asp:AccessDataSource ID="AccessDataSource2" runat="server" DataFile="~~/App_Data/northwind.mdb" SelectCommand="SELECT [ProductID], [ProductName], [SupplierID], [UnitPrice], [UnitsInStock], [Discontinued] FROM [Products] WHERE ([CategoryID] = ?)"> <asp:ControlParameter ControlID="DropDownList1" Name="CategoryID" PropertyName="SelectedValue" Type="Int32" />
Data-Driven - 69 © Minder Chen, ManageProduct.aspx
Data-Driven - 70 © Minder Chen, Add Edit and New Button
Data-Driven - 71 © Minder Chen, Make sure that Insert, Update, Delete statements are generated
Data-Driven - 72 © Minder Chen, Insert Problem Using Visual Web Developer 2005 and ASP.NET 2.0 If you insert an AccessDataSource that use a table for insert, update and delete operations and the table has a primary key that is an autonumber, the code that is generated is shown in the next 3 slides. If you want to insert a record (Using a DetailsView object) you get the following error: "You tried to assign the Null value to a variable that is not a Variant data type.". Bold & UnderlinedTo correct the problem, remove the highlighted (Bold & Underlined) code that has been generated. Source:
Data-Driven - 73 © Minder Chen, ManageProduct.aspx Untitled Page Manage Product Information <asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" AutoGenerateRows="False" DataKeyNames="ProductID" DataSourceID="AccessDataSource1" Height="50px" > <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" /> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />
Data-Driven - 74 © Minder Chen, Continued… <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = ?" InsertCommand="INSERT INTO [Products] [ProductID], ( [ProductID], [ProductName], [CategoryID], [UnitPrice], [Discontinued], [SupplierID], [QuantityPerUnit], [UnitsInStock], [UnitsOnOrder], [ReorderLevel]) ?, VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" SelectCommand="SELECT [ProductID], [ProductName], [CategoryID], [UnitPrice], [Discontinued], [SupplierID], [QuantityPerUnit], [UnitsInStock], [UnitsOnOrder], [ReorderLevel] FROM [Products]" UpdateCommand="UPDATE [Products] SET [ProductName] = ?, [CategoryID] = ?, [UnitPrice] = ?, [Discontinued] = ?, [SupplierID] = ?, [QuantityPerUnit] = ?, [UnitsInStock] = ?, [UnitsOnOrder] = ?, [ReorderLevel] = ? WHERE [ProductID] = ?">
Data-Driven - 75 © Minder Chen, Continued… Delete!!!
Data-Driven - 76 © Minder Chen, Data Binding In Templates Goal: Simpler data expression syntax for both simple and complex expressions V1 Databinding syntax – New Syntax – // one-way databinding – // two-way databinding
Data-Driven - 77 © Minder Chen, Data Binding in Templates Two-way data bindings –Enable templated controls to retrieve input values to use as parameters –Allow templated controls to perform automatic updates/deletes –GridView and DetailsView both support two- way data bindings using TemplateField –New FormView control allows completely templated rendering of DetailsView –Future ListView control would provide this behavior for DataList functionality
Data-Driven - 78 © Minder Chen, Use Template for Editing CategoryID
Data-Driven - 79 © Minder Chen, CategoryID Template ….. <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" /> <asp:Label ID="Label1" runat="server" Text=' '> <asp:TextBox ID="TextBox1" runat="server" Text=' '> <asp:TextBox ID="TextBox1" runat="server" Text=' '> <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" /> …..
Data-Driven - 80 © Minder Chen,
Data-Driven - 81 © Minder Chen, Set SelectedValue Properties
Data-Driven - 82 © Minder Chen, Modified Template '> <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="AccessDataSource1" DataTextField="CategoryName" DataValueField="CategoryID" SelectedValue=' '> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/northwind.mdb" SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]"> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CategoryID") %>'>
Data-Driven - 83 © Minder Chen, Indirect Events Indirect events can be raised by ASP.NET internally because of some action taken by the user. Deleting Is deleting allowed Cancel the event e.Cancel = True Deleted No Yes Run the event ' Handle exception gracefully If e.Exception IsNot Nothing Then AccessDataSource1_Deleted AccessDataSource1_Deleting
Data-Driven - 84 © Minder Chen, Handle Exception (Partial Code) Sub CustomersGridView_RowDeleted(ByVal sender As Object, ByVal e As GridViewDeletedEventArgs) ' Use the Exception property to determine whether an exception ' occurred during the delete operation. If e.Exception Is Nothing Then ' Use the AffectedRows property to determine whether the ' record was deleted. Sometimes an error might occur that ' does not raise an exception, but prevents the delete ' operation from completing. If e.AffectedRows = 1 Then Message.Text = "Record deleted successfully." Else Message.Text = "An error occurred during the delete operation." End If Else ' Insert the code to handle the exception. Message.Text = "An error occurred during the delete operation." ' Use the ExceptionHandled property to indicate that the ' exception is already handled. e.ExceptionHandled = True End If End Sub
Data-Driven - 85 © Minder Chen, GridViewDeletedEventArgs Example <asp:gridview id="CustomersGridView" datasourceid="CustomersSqlDataSource" autogeneratecolumns="true" autogeneratedeletebutton="true" datakeynames="CustomerID" onrowdeleted="CustomersGridView_RowDeleted" runat="server"> <asp:sqldatasource id="CustomersSqlDataSource" selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]" deletecommand="Delete from Customers where CustomerID connectionstring = " " runat="server">
Data-Driven - 86 © Minder Chen, Insert Issues Not pass an identity column during an insert to the database? –Set InsertVisible property of control to false After the insert, retrieve the newly inserted record, complete with identity column? –Uses Inserted event of DataSource control and grab the value of the identity column using e.Command.Parameters collection
Data-Driven - 87 © Minder Chen, Insert, Update, Delete Issues – Keep Controls in Sync Refresh one control when another changes? Call DataBind() method of second control from first control’s ItemInserted,ItemUpdated, or ItemDeleted event Protected Sub FormView1_ItemInserted(ByVal sender As Object, _ ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) If e.Exception IsNot Nothing Then LabelMsg.Text = "Insert failed. Reason: " & e.Exception.Message Else LabelMsg.Text = "Insert succeeded!" FormView1.Visible = False GridView1.DataBind() End If End Sub
Data-Driven - 88 © Minder Chen, Set a default value of a control for an insert Use DataBound event, checking the CurrentMode property Protected Sub FormView1_DataBound(ByVal sender As Object, _ ByVal e As System.EventArgs) ' Set default value of the supplier ID to the current supplier ID If (FormView1.CurrentMode = FormViewMode.Insert) Then CType(FormView1.FindControl("SUPIDLabel"), Label).Text = _ LabelSupplierID.Text End If End Sub