您好,登錄后才能下訂單哦!
這篇文章給大家介紹ASP.NET 2.0中怎么自定義DataList編輯界面,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
第一步: 顯示Product 信息
在創(chuàng)建DataList的編輯界面前,我們需要先創(chuàng)建一個只讀界面。先打開EditDeleteDataList文件夾下的CustomizedUI.aspx頁,拖一個DataList進來,將ID設(shè)為Products。通過DataList的智能標(biāo)簽,創(chuàng)建一個名為ProductsDataSource的ObjectDataSource,用ProductsBLL類的GetProducts方法配置它。象前面一章一樣,我們將直接通過BLL來更新product信息。在UPDATE,INSERT,DELETE標(biāo)簽里選擇None.
圖 2: 在UPDATE, INSERT, DELETE 標(biāo)簽的下拉列表里選擇 (None)
配置完ObjectDataSource后,Visual Studio會自動創(chuàng)建默認(rèn)的ItemTemplate,列出每個字段的值。將product name用<h5>表示,并添加一個Edit button,確保將它的CommandName屬性設(shè)為 “Edit”. 我的標(biāo)記語言如下:
<ItemTemplate> <h5> <asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' /> </h5> <table border="0"> <tr> <td class="ProductPropertyLabel">Category:</td> <td class="ProductPropertyValue"> <asp:Label ID="CategoryNameLabel" runat="server" Text='<%# Eval("CategoryName") %>' /> </td> <td class="ProductPropertyLabel">Supplier:</td> <td class="ProductPropertyValue"> <asp:Label ID="SupplierNameLabel" runat="server" Text='<%# Eval("SupplierName") %>' /> </td> </tr> <tr> <td class="ProductPropertyLabel">Discontinued:</td> <td class="ProductPropertyValue"> <asp:Label ID="DiscontinuedLabel" runat="server" Text='<%# Eval("Discontinued") %>' /> </td> <td class="ProductPropertyLabel">Price:</td> <td class="ProductPropertyValue"> <asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice", "{0:C}") %>' /> </td> </tr> <tr> <td colspan="4"> <asp:Button runat="Server" ID="EditButton" Text="Edit" CommandName="Edit" /> </td> </tr> </table> <br /> </ItemTemplate>
上面的標(biāo)記語言用<h5>表示product name,4列的<table>展示其它字段。前面已經(jīng)討論過Styles.css里定義的ProductPropertyLabel和productPropertyValue類。瀏覽該頁,見圖3。
圖 3: 顯示product信息
第二步: 為編輯界面添加web控件
首先向EditItemTemplate里添加需要的web控件。我們需要用一個DropDownList表示category,一個DropDownList表示supplier,一個CheckBox 表示discontinued state。由于本例中不用編輯price,所以仍然用Label來表示它。
點擊DataList的智能標(biāo)簽上的“Edit Templates”,選擇EditItemTemplate,為它添加一個ID為Categories的EditItemTemplate。
圖 4: 為Categories添加一個DropDownList
然后從DropDownList的智能標(biāo)簽里選擇“Choose Data Source”,創(chuàng)建一個名為CategoriesDataSource的ObjectDataSource。用CategoriesBLL類的GetCategories()方法配制它(見圖5)。數(shù)據(jù)源配置向?qū)鬄長istItem Text和Value選擇字段。讓DropDownList 顯示CategoryName,CategoryID作為Value,見圖6。
圖 5: 創(chuàng)建 ObjectDataSource
圖 6: 配置DropDownList的 Display 字段和Value 字段
重復(fù)上面的步驟,為suppliers創(chuàng)建一個ID為Suppliers的DropDownList 和一個名為SuppliersDataSource的ObjectDataSource。
然后為discontinued state 添加一個CheckBox ,為name添加一個TextBox 。將他們的ID分別設(shè)為Discontinued和ProductName。為product name添加一個RequiredFieldValidator 確保用戶必須提供這個值。
最后添加Update 和Cancel button。記得這兩個button的CommandName屬性必須分別設(shè)為“Update” 和“Cancel”。你可以將編輯界面以你喜歡的方式展示。我選擇使用和只讀界面一樣的界面來顯示,見下面的聲明代碼和截圖。
<EditItemTemplate> <h5> <asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' /> </h5> <table border="0"> <tr> <td class="ProductPropertyLabel">Name:</td> <td colspan="3" class="ProductPropertyValue"> <asp:TextBox runat="server" ID="ProductName" Width="90%" /> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="ProductName" ErrorMessage="You must enter a name for the product." runat="server">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td class="ProductPropertyLabel">Category:</td> <td class="ProductPropertyValue"> <asp:DropDownList ID="Categories" runat="server" DataSourceID="CategoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" /> </td> <td class="ProductPropertyLabel">Supplier:</td> <td class="ProductPropertyValue"> <asp:DropDownList ID="Suppliers" DataTextField="CompanyName" DataSourceID="SuppliersDataSource" DataValueField="SupplierID" runat="server" /> </td> </tr> <tr> <td class="ProductPropertyLabel">Discontinued:</td> <td class="ProductPropertyValue"> <asp:CheckBox runat="server" id="Discontinued" /> </td> <td class="ProductPropertyLabel">Price:</td> <td class="ProductPropertyValue"> <asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice", "{0:C}") %>' /> </td> </tr> <tr> <td colspan="4"> <asp:Button runat="Server" ID="UpdateButton" CommandName="Update" Text="Update" /> <asp:Button runat="Server" ID="CancelButton" CommandName="Cancel" Text="Cancel" CausesValidation="False" /> </td> </tr> </table> <br /> <asp:ObjectDataSource ID="CategoriesDataSource" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetCategories" TypeName="CategoriesBLL"> </asp:ObjectDataSource> <asp:ObjectDataSource ID="SuppliersDataSource" runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetSuppliers" TypeName="SuppliersBLL"> </asp:ObjectDataSource> </EditItemTemplate>
圖 7: 編輯界面和只讀界面的展示差不多
第三步: 創(chuàng)建 EditCommand和CancelCommand Event Handlers
現(xiàn)在在EditItemTemplate里除了UnitPriceLabel外還沒有綁定語法(從ItemTemplate復(fù)制過來的代碼)。在添加綁定語法前我們首先為DataList的EditCommand和CancelCommand創(chuàng)建事件處理。EditCommand事件處理的目標(biāo)是為了將Edit button被點擊的item展示為編輯狀態(tài),而CancelCommand的目標(biāo)是將DataList返回到編輯前狀態(tài)。見下面的代碼:
protected void Products_EditCommand(object source, DataListCommandEventArgs e) { // Set the DataList's EditItemIndex property and rebind the data Products.EditItemIndex = e.Item.ItemIndex; Products.DataBind(); } protected void Products_CancelCommand(object source, DataListCommandEventArgs e) { // Return to DataList to its pre-editing state Products.EditItemIndex = -1; Products.DataBind(); }
完成這些后,點擊Edit button會進入編輯界面,點擊Cancel button會返回只讀模式。見圖8。由于現(xiàn)在還沒有為編輯界面添加綁定語法,TextBox是空白的,CheckBox 未被選中,兩個DropDownList里都是第一個item被選中。
圖 8: 點擊Edit Button顯示編輯界面
第四步: 為編輯界面增加綁定語法
為了讓編輯界面顯示當(dāng)前product的值,我們需要使用綁定語法將字段的值賦給web控件。綁定語法可以通過選擇web控件的智能標(biāo)簽的“Edit DataBindings”或者直接添加聲明語法來實現(xiàn)。
將ProductName字段的值賦給ProductName TextBox的Text屬性,CategoryID和SupplierID字段賦給Categories和Suppliers DropDownList的SelectedValue屬性,Discontinued字段賦給Discontinued CheckBox的Checked屬性。完成這些后,瀏覽頁面并點擊Edit button.見圖9。
圖 9: 點擊Edit Button 顯示編輯界面
第五步: 在UpdateCommand Event Handler保存用戶的更改
當(dāng)用戶編輯product并點Update button后,會postback并激發(fā)UpdateCommand事件。在事件處理里,我們需要從EditItemTemplate里讀出web控件的值,并和BLL交互,然后更新數(shù)據(jù)庫里的product。如我們在前面一章看到的那樣,被更新的product的ProductID可以通過DataKeys集合來獲取。用戶輸入的值可以通過FindControl("controlID")來編程獲取,見下面的代碼:
protected void Products_UpdateCommand(object source, DataListCommandEventArgs e) { // Make sure the page is valid... if (!Page.IsValid) return; // Read in the ProductID from the DataKeys collection int productID = Convert.ToInt32(Products.DataKeys[e.Item.ItemIndex]); // Read in the product name and price values TextBox productName = (TextBox)e.Item.FindControl("ProductName"); DropDownList categories = (DropDownList)e.Item.FindControl("Categories"); DropDownList suppliers = (DropDownList)e.Item.FindControl("Suppliers"); CheckBox discontinued = (CheckBox)e.Item.FindControl("Discontinued"); string productNameValue = null; if (productName.Text.Trim().Length > 0) productNameValue = productName.Text.Trim(); int categoryIDValue = Convert.ToInt32(categories.SelectedValue); int supplierIDValue = Convert.ToInt32(suppliers.SelectedValue); bool discontinuedValue = discontinued.Checked; // Call the ProductsBLL's UpdateProduct method... ProductsBLL productsAPI = new ProductsBLL(); productsAPI.UpdateProduct(productNameValue, categoryIDValue, supplierIDValue, discontinuedValue, productID); // Revert the DataList back to its pre-editing state Products.EditItemIndex = -1; Products.DataBind(); }
代碼首先檢查Page.IsValid屬性來確保所有的驗證控件都返回合法值。如果Page.IsValid為True,從DataKeys集合里讀出被編輯的product 的ProductID的值,并引用EditItemTemplate里的web控件。然后將這些控件的值讀到變量里,并傳給UpdateProduct方法。完成更新后,DataList會返回到編輯前的狀態(tài)。
注意:我省略了某章異常處理,目的是為了使本章的代碼看起來目的性更強。你可以在完成本章后自己添加異常處理的功能作為練習(xí)。
第六步: 處理空的CategoryID 和SupplierID 值
Northwind 數(shù)據(jù)庫允許Products表里的CategoryID和SupplierID列為空。然而我們的編輯界面目前還沒有提供可選空值。如果我們試圖編輯一個無論是CategoryID還是SupplierID為空的product,將會產(chǎn)生ArgumentOutOfRangeException異常。目前我們也沒有將product的category或supplier的值從一個非空值轉(zhuǎn)換為空值的方法。
為了在DropDownLists里添加空值,我們需要添加一個ListItem。我將ListItem里的Text顯示為"(None)",你可以將它賦為任何你希望的值(比如空字符串)。最后,記得將DropDownLists的AppendDataBoundItems設(shè)為True。如果你沒有這么做,綁定到DropDownList 的categories 和suppliers 會被添加的ListItem覆蓋。完成這些后,DropDownLists的標(biāo)記語言看起來應(yīng)該和下面差不多:
<asp:DropDownList ID="Categories" DataSourceID="CategoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" runat="server" SelectedValue='<%# Eval("CategoryID") %>' AppendDataBoundItems="True"> <asp:ListItem Value=" Selected="True">(None)</asp:ListItem> </asp:DropDownList> ... <asp:DropDownList ID="Suppliers" DataSourceID="SuppliersDataSource" DataTextField="CompanyName" DataValueField="SupplierID" runat="server" SelectedValue='<%# Eval("SupplierID") %>' AppendDataBoundItems="True"> <asp:ListItem Value=" Selected="True">(None)</asp:ListItem> </asp:DropDownList>
注意:為DropDownList 添加ListItems可以通過設(shè)計器或者聲明語法來完成。當(dāng)添加一個表示數(shù)據(jù)庫空值的item時,要確保是通過聲明語法來完成的。如果你使用設(shè)計器的ListItem集合編輯器,當(dāng)賦空字符串時,產(chǎn)生的聲明語法會忽略Value的設(shè)置,產(chǎn)生想<asp:ListItem>(None)</asp:ListItem>這樣的語句。這個看起來并沒有什么關(guān)系,但是缺少Value會讓DropDownList 使用Text屬性的值作為Value。這意味著當(dāng)NULL ListItem被選擇時,“(None)” 會被賦給product的CategoryID或SupplierID字段,這會引起異常。而顯式的將Value設(shè)為“”,當(dāng)NULL ListItem被選擇時一個空值會被賦給product的CategoryID或SupplierID字段?,F(xiàn)在瀏覽該頁。當(dāng)編輯product時,注意Categories和Suppliers DropDownLists 開頭都包含一個“(None)”選項。
圖 10: Categories 和Suppliers DropDownLists包含 “(None)”
為了將“(None)” 保存為數(shù)據(jù)庫NULL值,我們需要回到UpdateCommand事件處理。將categoryIDValue和supplierIDValue變量設(shè)為可為空的整型,并在DropDownList的SelectedValue的值不為空字符串時才為它們賦值。
int? categoryIDValue = null; if (!string.IsNullOrEmpty(categories.SelectedValue)) categoryIDValue = Convert.ToInt32(categories.SelectedValue); int? supplierIDValue = null; if (!string.IsNullOrEmpty(suppliers.SelectedValue)) supplierIDValue = Convert.ToInt32(suppliers.SelectedValue);
關(guān)于ASP.NET 2.0中怎么自定義DataList編輯界面就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。