主頁 > 知識庫 > 在ASP.NET 2.0中操作數(shù)據(jù)之三十六:在DataList里編輯和刪除數(shù)據(jù)概述

在ASP.NET 2.0中操作數(shù)據(jù)之三十六:在DataList里編輯和刪除數(shù)據(jù)概述

熱門標(biāo)簽:解決方案 電子圍欄 硅谷的囚徒呼叫中心 蘋果 地方門戶網(wǎng)站 服務(wù)器配置 智能手機(jī) 呼叫中心

導(dǎo)言

  概述插入、更新和刪除數(shù)據(jù) 里我們已經(jīng)學(xué)習(xí)了如何使用GridView等控件來插入,更新刪除數(shù)據(jù)。通過ObjectDataSource和其它數(shù)據(jù)控件僅僅只需要在智能標(biāo)簽里勾一下checkbox就完成了,不需要寫任何代碼。而DataList沒有這些內(nèi)置的功能。我們可以使用1.x 里的方法來實(shí)現(xiàn)這些功能。在本章我們將看到,DataList提供了一些事件和屬性來完成我們的目的,為此我們需要寫一些代碼。

  本章我們首先學(xué)習(xí)如何創(chuàng)建一個(gè)支持編輯和刪除數(shù)據(jù)的DataList。后面的教程里我們將學(xué)習(xí)一些高級的編輯和刪除方法,包括驗(yàn)證,DAL和BLL的異常處理等。

  注意:和DataList一樣,Repeater也不提供內(nèi)置的這些功能。而且Repeater里沒有DataList里提供的那些事件和屬性。因此本章和后面的幾章我們僅僅只討論DataList。

第一步: 創(chuàng)建編輯和刪除教程頁

  首先創(chuàng)建本章和后面幾章需要用到的頁。添加一個(gè)名為EditDeleteDataList的文件夾。然后添加下面的頁。確保每頁都包含了Site.master。

Default.aspx
Basics.aspx
BatchUpdate.aspx
ErrorHandling.aspx
UIValidation.aspx
CustomizedUI.aspx
OptimisticConcurrency.aspx
ConfirmationOnDelete.aspx
UserLevelAccess.aspx


圖 1: 添加頁

  和別的文件夾一樣,Default.aspx列出教程章節(jié)。記得SectionLevelTutorialListing.ascx用戶控件提供了這個(gè)功能。從解決方案里將它拖到我們的頁里。


圖 2: 添加SectionLevelTutorialListing.ascx 用戶控件

  最后將這些頁添加到Web.sitemap里。在Master/Detail Reports with the DataList and RepeatersiteMapNode>之后添加下面的標(biāo)記:

siteMapNode
 title="Editing and Deleting with the DataList"
 description="Samples of Reports that Provide Editing and Deleting Capabilities"
 url="~/EditDeleteDataList/Default.aspx" >
 siteMapNode
 title="Basics"
 description="Examines the basics of editing and deleting with the
   DataList control."
 url="~/EditDeleteDataList/Basics.aspx" />
 siteMapNode
 title="Batch Update"
 description="Examines how to update multiple records at once in a
   fully-editable DataList."
 url="~/EditDeleteDataList/BatchUpdate.aspx" />
 siteMapNode
 title="Error Handling"
 description="Learn how to gracefully handle exceptions raised during the
   data modification workflow."
 url="~/EditDeleteDataList/ErrorHandling.aspx" />
 siteMapNode
 title="Adding Data Entry Validation"
 description="Help prevent data entry errors by providing validation."
 url="~/EditDeleteDataList/UIValidation.aspx" />
 siteMapNode
 title="Customize the User Interface"
 description="Customize the editing user interfaces."
 url="~/EditDeleteDataList/CustomizedUI.aspx" />
 siteMapNode
 title="Optimistic Concurrency"
 description="Learn how to help prevent simultaneous users from
   overwritting one another s changes."
 url="~/EditDeleteDataList/OptimisticConcurrency.aspx" />
 siteMapNode
 title="Confirm On Delete"
 description="Prompt a user for confirmation when deleting a record."
 url="~/EditDeleteDataList/ConfirmationOnDelete.aspx" />
 siteMapNode
 title="Limit Capabilities Based on User"
 description="Learn how to limit the data modification functionality
   based on the user s role or permissions."
 url="~/EditDeleteDataList/UserLevelAccess.aspx" />
/siteMapNode>

更新了Web.sitemap后,瀏覽一下。


圖 3: 站點(diǎn)導(dǎo)航現(xiàn)在包含了編輯和刪除DataList 教程

第二步: 探討更新和刪除數(shù)據(jù)所要用到的技術(shù)

  使用GridView來編輯和刪除數(shù)據(jù)之所以很簡單,是因?yàn)镚ridView和ObjectDataSource在底層非常一致。如研究插入、更新和刪除的關(guān)聯(lián)事件里所討論的,當(dāng)更新按鈕被點(diǎn)擊時(shí),GridView自動(dòng)將字段的值賦給ObjectDataSource的UpdateParameters集合,然后激發(fā)ObjectDataSource的Update()方法。我們現(xiàn)在需要確保將合適的值賦給ObjectDataSource的參數(shù),然后調(diào)用Update()方法。DataList提供了以下的屬性和事件來幫助我們完成這些:

  DataKeyField property — 更新或刪除時(shí),我們需要唯一確定DataList里的每個(gè)item。將這個(gè)屬性設(shè)為顯示的數(shù)據(jù)的主健。這樣做會(huì)產(chǎn)生DataList的 DataKeys collection ,每個(gè)item都有一個(gè)指定的 DataKeyField .
 EditCommand event — 當(dāng)CommandName屬性設(shè)為“Edit”的Button, LinkButton, 或 ImageButton 被點(diǎn)時(shí)激發(fā).
 CancelCommand event — 當(dāng)CommandName屬性設(shè)為“Cancel”的Button, LinkButton, 或 ImageButton 被點(diǎn)時(shí)激發(fā). UpdateCommand event — 當(dāng)CommandName屬性設(shè)為“Update”的Button, LinkButton, 或 ImageButton 被點(diǎn)時(shí)激發(fā).  DeleteCommand event — 當(dāng)CommandName屬性設(shè)為“Delete”的Button, LinkButton, 或 ImageButton 被點(diǎn)時(shí)激發(fā).

  使用以上的屬性和事件,我們有四種方法來更新和刪除數(shù)據(jù):

  使用ASP.NET 1.x 的技術(shù)— DataList先于ASP.NET 2.0 和ObjectDataSources 存在,可以直接通過編程來實(shí)現(xiàn)編輯和刪除。這種方法需要我們在顯示數(shù)據(jù)或者更新刪除記錄時(shí),直接在BLL層將數(shù)據(jù)綁定到DataList。
使用一個(gè)單獨(dú)的ObjectDataSource 來實(shí)現(xiàn)選擇,更新和刪除 — DataList沒有GridView內(nèi)置的編輯刪除功能,并不意味著我們不能添加這些功能。我們象在GridView的例子里那樣,使用 ObjectDataSource,但是在設(shè)置ObjectDataSource的參數(shù)并調(diào)用Update()方法時(shí),需要為DataList的UpdateCommand事件創(chuàng)建一個(gè)  event handler。 Using an ObjectDataSource Control for Selecting, but Updating and Deleting Directly Against the BLL — 使用第二種方法時(shí)我們需要為UpdateCommand事件和參數(shù)賦值等寫一些代碼。其實(shí)我們可以用ObjectDataSource來實(shí)現(xiàn)selecting ,更新和刪除直接調(diào)用BLL(象第一種方法)。我的意見是,直接調(diào)用BLL會(huì)使代碼可讀性更好。 使用多個(gè)ObjectDataSources —前面的三種方法都需要一些代碼。如果你寧愿堅(jiān)持使用盡可能多的聲明語法的話,最后一種方法是使用多個(gè)ObjectDataSources 。第一個(gè)ObjectDataSource 從BLL獲取數(shù)據(jù),并綁定到 DataList. 為更新添加另一個(gè) ObjectDataSource, 直接添加到 DataList的 EditItemTemplate.同樣對刪除也是如此。三個(gè) ObjectDataSource通過 ControlParameters   聲明語法直接將參數(shù)綁定到ObjectDataSource 的參數(shù) (而不是在 DataList的 UpdateCommand event handler編程處理). 這種方法也需要一些編碼 — 我們需要調(diào)用 ObjectDataSource內(nèi)置的 Update() 或 Delete() — 但是比起其它三種方法,代碼少的多。這種方法的劣勢是多個(gè)  ObjectDataSources 使頁面看起來混亂。

   我喜歡選擇第一種方法,因?yàn)樗峁┝烁玫目蓴U(kuò)展性,而設(shè)計(jì)DataList的本意就是使用這種方式。當(dāng)擴(kuò)展DataList使它和ASP.NET 2.0的數(shù)據(jù)源控件一起工作時(shí),它沒有“正式”的ASP.NET 2.0數(shù)據(jù)控件( GridView, DetailsView, 和FormView)的那些可擴(kuò)展性或特性。當(dāng)然其它方法也不是沒有優(yōu)點(diǎn)。

  這幾章關(guān)于編輯和刪除的教程會(huì)使用ObjectDataSource 來顯示數(shù)據(jù),然后直接調(diào)用BLL來實(shí)現(xiàn)編輯和刪除(第三種方法)

第三步: 添加DataList并配置它的ObjectDataSource

  本章我們將創(chuàng)建一個(gè)DataList用來列出product的信息,并提供用戶編輯其name和price,刪除的功能。我們使用ObjectDataSource來顯示數(shù)據(jù),調(diào)用BLL來實(shí)現(xiàn)更新和刪除的功能。首先我們來實(shí)現(xiàn)一個(gè)只讀的顯示product的頁。由于在前面的教程里已經(jīng)實(shí)現(xiàn)過這樣的功能,在這里我們很快帶過。

  打開EditDeleteDataList文件夾下的Basics.aspx頁,添加一個(gè)DataList。然后通過智能標(biāo)簽創(chuàng)建一個(gè)ObjectDataSource。在SELECT標(biāo)簽里使用ProductsBLL類的GetProducts()方法配置它。


圖 4: 使用ProductBLL類配置ObjectDataSource


圖 5: 選擇GetProducts()

在INSERT,UPDATE和DELETE標(biāo)簽里都選擇None。


圖 6: 在INSERT, UPDATE, 和DELETE 標(biāo)簽里選擇(None)

  完成配置后回到設(shè)計(jì)界面。如我們在以前的例子里看到的那樣,Visual Studio 會(huì)自動(dòng)創(chuàng)建ItemTemplate,顯示數(shù)據(jù)。將ItemTemplate改為只顯示product的name和price。然后將RepeatColumns設(shè)為2。

  注意:象以前討論的那樣,當(dāng)使用ObjectDataSource修改數(shù)據(jù)時(shí),我們在聲明標(biāo)記里需要移除OldValuesParameterFormatString (或重新設(shè)為缺省值,{0})。而本章ObjectDataSource僅僅只用來獲取數(shù)據(jù),因此不需要那樣做(當(dāng)然那樣做了也沒關(guān)系)。完成后你的頁代碼看起來應(yīng)該和下面差不多:

asp:DataList ID="DataList1" runat="server" DataKeyField="ProductID"
 DataSourceID="ObjectDataSource1" RepeatColumns="2">
 ItemTemplate>
 h5>
  asp:Label runat="server" ID="ProductNameLabel"
  Text='%# Eval("ProductName") %>'>/asp:Label>
 /h5>
 Price: asp:Label runat="server" ID="Label1"
   Text='%# Eval("UnitPrice", "{0:C}") %>' />
 br />
 br />
 /ItemTemplate>
/asp:DataList>
asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
 SelectMethod="GetProducts" TypeName="ProductsBLL"
 OldValuesParameterFormatString="original_{0}">
/asp:ObjectDataSource>

瀏覽一下頁面。如圖7,DataList以兩列的方式顯示product的name和price。


圖 7:  DataList顯示Products的 Names and Prices

  注意:DataList有一些屬性是編輯和刪除需要用到的,這些值都存在view state里。因此創(chuàng)建支持編輯和刪除功能的DataList時(shí),DataList的view state需要開啟。

  聰明的讀者應(yīng)該記起來在創(chuàng)建可編輯的GridView,DetailsViews和FormViews的時(shí)候,view state是禁用的。這是因?yàn)锳SP.NET 2.0 控件包含了control state,它在postback時(shí)狀態(tài)是連續(xù)的。

  在GridView里禁用了view state僅僅只是忽略了無關(guān)緊要的狀態(tài)信息,但是維持了control state(它包含了編輯和刪除需要的狀態(tài))。而DataList是 ASP.NET 1.x時(shí)代創(chuàng)建的,并沒有使用control state,因此view state必須開啟。更多的control state的目的以及和view state的區(qū)別信息見Control State vs. View State

第四步: 添加一個(gè)編輯界面

  GridView控件是由字段集合組成的(BoundFields, CheckBoxFields, TemplateFields等)。這些字段能根據(jù)模式來調(diào)整標(biāo)記。比如,在只讀模式下,BoundField 將字段值顯示為文本,而在編輯模式下,它將顯示為一個(gè)TextBox,這個(gè)TextBox的Text屬性被賦予字段的值。

  另一方面,DataList用template來展現(xiàn)它的item。只讀的item用ItemTemplate來展現(xiàn)。而當(dāng)在編輯模式下時(shí),item用EditItemTemplate來展示?,F(xiàn)在我們的DataList只有一個(gè)ItemTemplate。我們需要添加一個(gè)EditItemTemplate來支持編輯功能。本章我們使用TextBox來編輯product的name和price??梢酝ㄟ^聲明語言或設(shè)計(jì)視圖(DataList的智能標(biāo)簽的EditTemplate選項(xiàng))來創(chuàng)建EditItemTemplate。


圖 8:選擇EditItemTemplate


  然后輸入“Product name:” 和“Price:” ,再拖兩個(gè)TextBox到EditItemTemplate。將TextBox的ID屬性設(shè)為ProductName和UnitPrice。


圖 9:  添加TextBox


  我們需要將product的字段綁定到關(guān)聯(lián)的TextBox。在TextBox的智能標(biāo)簽上點(diǎn)擊Edit DataBindings,然后將Text屬性和適當(dāng)?shù)淖侄侮P(guān)聯(lián)。見圖10。

  注意:將UnitPrice綁定到TextBox時(shí),你可以用({0:C})將它 格式化為貨幣值,或用({0:N})表示為普通數(shù)字,或者不格式化。


圖 10:綁定字段到TextBoxes


  注意:圖10里的Edit DataBindings對話框里并不包含“雙向數(shù)據(jù)綁定”的checkbox,而在編輯GridView或DetailsVIew里的TemplateField,或者FormView里的template里時(shí)是有這個(gè)checkbox的。雙向數(shù)據(jù)綁定允許在插入或更新數(shù)據(jù)時(shí),輸入控件的值自動(dòng)賦給相關(guān)聯(lián)的ObjectDataSource的InsertParameters或UpdateParameters。DataList并不支持雙向綁定—我們在后面會(huì)看到,在用戶作出更改,準(zhǔn)備更新數(shù)據(jù)時(shí),我們需要編程將Textbox的Text的值傳給ProductsBLL類的UpdateProduct方法。


  最后我們在EditItemTemplate里加入U(xiǎn)pdate和Cancel按鈕。象前面看到的那樣,當(dāng)設(shè)置了CommandName的Repeater或DataList里的Button,LinkButton或ImageButton被點(diǎn)擊時(shí),Repeater或DataList的ItemCommand事件被激發(fā)。對DataList來說,如果CommandName設(shè)為某個(gè)值,另外一個(gè)事件也會(huì)被激發(fā),如下:


“Cancel” — 激發(fā) CancelCommand event
“Edit” — 激發(fā) EditCommand event
“Update” — 激發(fā)UpdateCommand event

  記住除了ItemCommand外,這些事件會(huì)激發(fā)。

  為EditItemTemplate添加兩個(gè)Button,一個(gè)CommandName設(shè)為"Update",一個(gè)設(shè)為"Cancel"。完成后,設(shè)計(jì)界面看起來應(yīng)該和下面差不多:


圖 11: 為 EditItemTemplate 添加Update 和Cancel 按鈕

你的標(biāo)記語言看起來應(yīng)該和下面差不多:

asp:DataList ID="DataList1" runat="server" DataKeyField="ProductID"
 DataSourceID="ObjectDataSource1" RepeatColumns="2">
 ItemTemplate>
 h5>
  asp:Label runat="server" ID="ProductNameLabel"
  Text='%# Eval("ProductName") %>' />
 /h5>
 Price: asp:Label runat="server" ID="Label1"
   Text='%# Eval("UnitPrice", "{0:C}") %>' />
 br />
 br />
 /ItemTemplate>
 EditItemTemplate>
 Product name:
  asp:TextBox ID="ProductName" runat="server"
  Text='%# Eval("ProductName") %>' />br />
 Price:
  asp:TextBox ID="UnitPrice" runat="server"
  Text='%# Eval("UnitPrice", "{0:C}") %>' />br />
 br />
 asp:Button ID="UpdateProduct" runat="server"
  CommandName="Update" Text="Update" /> 
 asp:Button ID="CancelUpdate" runat="server"
  CommandName="Cancel" Text="Cancel" />
 /EditItemTemplate>
/asp:DataList>
   

第五步: 添加進(jìn)入編輯模式的入口

  現(xiàn)在我們的DataList有一個(gè)編輯界面了。然而現(xiàn)在還沒有辦法來體現(xiàn)出用戶需要編輯product信息。我們需要為每個(gè)product加一個(gè)Edit button,當(dāng)點(diǎn)擊時(shí),將DataList item展示為編輯模式。同樣的可以通過設(shè)計(jì)器或直接聲明代碼來添加。確保將Edit button的commandName屬性設(shè)為"Edit".添加完后,瀏覽一下頁面。


圖 12: 添加Edit Buttons

  點(diǎn)擊button會(huì)引起postback,但是并沒有進(jìn)入product的編輯模式。為了完成這個(gè),我們需要:

  設(shè)置DataList的 EditItemIndex property 為 被點(diǎn)擊了Edit button的 DataListItem的 index .
  重新綁定數(shù)據(jù)到 DataList. 當(dāng) DataList 重新展現(xiàn)時(shí), 和DataList的EditItemIndex相關(guān)的DataListItem 會(huì)展現(xiàn)EditItemTemplate.

  由于在點(diǎn)Edit button時(shí),DataList的EditCommand事件被激發(fā),使用下面的代碼創(chuàng)建一個(gè)EditCommand event handler :

protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
{
    // Set the DataList's EditItemIndex property to the
    // index of the DataListItem that was clicked
    DataList1.EditItemIndex = e.Item.ItemIndex;
    // Rebind the data to the DataList
    DataList1.DataBind();
}
           

  EditCommand event handler 的第二個(gè)參數(shù)類型為DataListCommandEventArgs ,它是被點(diǎn)擊的Edit button的DataListItem的引用(e.Item).首先設(shè)置DataList的EditItemIndex為想編輯的DataListItem的ItemIndex,然后重新綁定數(shù)據(jù)。完成后再瀏覽頁面。點(diǎn)Edit button,現(xiàn)在product變成了可編輯的。見圖13。


圖 13: 點(diǎn)Edit Button 使Product 可編輯

第六步: 保存用戶的更改

  現(xiàn)在點(diǎn)product的Update或Cancel button不會(huì)有任何反應(yīng)。為了完成目標(biāo)我們需要為DataList的UpdateCommand和CancelCommand創(chuàng)建event handler。首先創(chuàng)建CancelCommand event handler,它在product的Cancel button點(diǎn)擊時(shí)執(zhí)行,使DataList返回編輯之前的狀態(tài)。使DataList以只讀模式展示item,我們需要:

  設(shè)置DataList的 EditItemIndex property 為一個(gè)不存在的DataListItem index -1是一個(gè)好的選擇。(由于DataListItem index從0開始) 重新綁定數(shù)據(jù)到DataList。由于沒有DataListItem ItemIndex和DataList的EditItemIndex關(guān)聯(lián),整個(gè)DataList會(huì)展現(xiàn)為只讀模式。 這些可以通過以下代碼完成:

protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
{
 // Set the DataList's EditItemIndex property to -1
 DataList1.EditItemIndex = -1;
 // Rebind the data to the DataList
 DataList1.DataBind();
}

現(xiàn)在點(diǎn)擊Cancel button會(huì)返回到DataList編輯前的狀態(tài)。

最后我們來完成UpdateCommand event handler,我們需要:

編程獲取用戶輸入的product name和price,還有ProductID.
調(diào)用ProductsBLL類里的合適的UpdateProduct重載方法.
設(shè)置DataList的EditItemIndex property 為一個(gè)不存在的DataListItem index. -1 是一個(gè)好的選擇。
重新幫頂數(shù)據(jù)。

  第一和第二步負(fù)責(zé)保存用戶的更改。第三步返回到DataList編輯前的狀態(tài)(和CancelCommand event handler一樣)。

  我們需要使用FindControl方法來獲取product的name和price(當(dāng)然包括ProductID)。當(dāng)最初將ObjectDataSource綁定到DataList時(shí),Visual Studio 將DataList的DataKeyField 屬性賦為數(shù)據(jù)源的主鍵值(ProductID)。這個(gè)值可以通過DataList的DataKey集合來獲取。花點(diǎn)時(shí)間驗(yàn)證一下DataKeyField 是否設(shè)置為ProductID。

下面的代碼完成了上面的功能:

protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
{
 // Read in the ProductID from the DataKeys collection
 int productID = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
 // Read in the product name and price values
 TextBox productName = (TextBox)e.Item.FindControl("ProductName");
 TextBox unitPrice = (TextBox)e.Item.FindControl("UnitPrice");
 string productNameValue = null;
 if (productName.Text.Trim().Length > 0)
 productNameValue = productName.Text.Trim();
 decimal? unitPriceValue = null;
 if (unitPrice.Text.Trim().Length > 0)
 unitPriceValue = Decimal.Parse(unitPrice.Text.Trim(),
  System.Globalization.NumberStyles.Currency);
 // Call the ProductsBLL's UpdateProduct method...
 ProductsBLL productsAPI = new ProductsBLL();
 productsAPI.UpdateProduct(productNameValue, unitPriceValue, productID);
 // Revert the DataList back to its pre-editing state
 DataList1.EditItemIndex = -1;
 DataList1.DataBind();
}

  首先從DataKeys集合里讀出product的ProductID。然后將兩個(gè)TextBox的Text屬性存起來。我們用Decimal.Parse() 方法去讀UnitPrice TextBox的值,以便在這個(gè)值有貨幣符號時(shí)可以正確的轉(zhuǎn)換。

  注意:只有在TextBox的Text指定了值的情況下,productNameValue和unitPriceValue變量才會(huì)被賦值。否則,會(huì)在更新數(shù)據(jù)時(shí)使用一個(gè)NULL值。也就是說我們的代碼會(huì)將空字符串轉(zhuǎn)換為NULL值,而在GridView,DetailsView和FormView控件的編輯界面里NULL是缺省值。獲取值后,調(diào)用ProductsBLL類的UpdateProduct方法,將product的name,price和ProductID傳進(jìn)去。使用和CancelCommand event handler里同樣的邏輯返回到DataList編輯前狀態(tài)。完成了EditCommand,CancelCommand和UpdateCommand event handler后,用戶可以編輯product的name和price了。見圖14。


圖 14: 瀏覽頁時(shí)所有的Products都是只讀模式


圖 15: 點(diǎn)擊Edit Button


圖 16: 改變值后,點(diǎn)擊 Update返回只讀模式

第七步: 增加刪除功能

增加刪除功能的步驟和增加編輯功能差不多。簡單來說我們需要在ItemTemplate里添加一個(gè)Delete button,當(dāng)點(diǎn)擊時(shí):

從DataKeys 集合里讀取關(guān)聯(lián)的proudct的ProductID .
調(diào)用ProductsBLL class的DeleteProduct 方法執(zhí)行刪除操作.
重新綁定數(shù)據(jù)到 DataList.
首先來增加一個(gè)Delete button.

  當(dāng)點(diǎn)擊一個(gè)CommandName為“Edit”, “Update”, 或“Cancel”的Button時(shí),會(huì)激發(fā)DataList的ItemCommand事件和另外一個(gè)事件(比如,使用“Edit”時(shí)EditCommand 事件會(huì)被激發(fā))。同樣的,CommandName為“Delete”時(shí)會(huì)激發(fā)DeleteCommand 事件(和ItemCommand一起)。

在Edit button后面增加一個(gè)Delete button ,將CommandName屬性設(shè)為“Delete”. 完成后聲明代碼如下:

ItemTemplate>
 h5>
 asp:Label runat="server" ID="ProductNameLabel"
  Text='%# Eval("ProductName") %>' />
 /h5>
 Price: asp:Label runat="server" ID="Label1"
  Text='%# Eval("UnitPrice", "{0:C}") %>' />
 br />
 asp:Button runat="server" id="EditProduct" CommandName="Edit"
 Text="Edit" />
 
 asp:Button runat="server" id="DeleteProduct" CommandName="Delete"
 Text="Delete" />
 br />
 br />
/ItemTemplate>

然后為DataList的DeleteCommand事件創(chuàng)建一個(gè)event handler,見下面的代碼:

protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
{
 // Read in the ProductID from the DataKeys collection
 int productID = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
 // Delete the data
 ProductsBLL productsAPI = new ProductsBLL();
 productsAPI.DeleteProduct(productID);
 // Rebind the data to the DataList
 DataList1.DataBind();
}
        

  點(diǎn)擊Delete button 會(huì)引起postback,并激發(fā)DataList的DeleteCommand事件。在事件處理中,被點(diǎn)擊的product的ProductID的值通過DateKeys集合來獲取。然后,調(diào)用ProductsBLL類的DeleteProduct方法來刪除product。刪除product后,要將數(shù)據(jù)重新綁定到DataList(DataList1.DataBind()),否則DataList里還會(huì)看到剛才刪除的product。

總結(jié)

  通過少量的代碼,DataList也可以擁有GridView的編輯刪除功能。在本章我們學(xué)習(xí)了如何創(chuàng)建一個(gè)兩列的顯示product的頁,并且可以編輯name和price,刪除product。增加編輯和刪除功能需要在ItemTemplate和EditItemTemplate里增加合適的控件,創(chuàng)建對應(yīng)的事件處理,讀取用戶的輸入和主鍵值,然后調(diào)用BLL。

  雖然我們?yōu)镈ataList增加了基本的編輯和刪除功能,它還是缺少一些高級特性。比如,沒有輸入字段驗(yàn)證- 如果用戶輸入的price太“貴”,Decimal.Parse在轉(zhuǎn)換為Decimal時(shí)會(huì)拋出異常。同樣的,如果在更新數(shù)據(jù)時(shí),BLL或DAL里有異常,用戶會(huì)看到系統(tǒng)錯(cuò)誤。在刪除時(shí)沒有任何確認(rèn),很可能會(huì)誤刪數(shù)據(jù)。在后面的教程里我們會(huì)學(xué)習(xí)如何改善這些問題。

  祝編程快樂!

作者簡介

  本系列教程作者 Scott Mitchell,著有六本ASP/ASP.NET方面的書,是4GuysFromRolla.com的創(chuàng)始人,自1998年以來一直應(yīng)用 微軟Web技術(shù)。大家可以點(diǎn)擊查看全部教程《[翻譯]Scott Mitchell 的ASP.NET 2.0數(shù)據(jù)教程》,希望對大家的學(xué)習(xí)ASP.NET有所幫助。

您可能感興趣的文章:
  • asp.net中使用 Repeater控件拖拽實(shí)現(xiàn)排序并同步數(shù)據(jù)庫字段排序
  • 在ASP.NET 2.0中操作數(shù)據(jù)之三十四:基于DataList和Repeater跨頁面的主/從報(bào)表
  • 在ASP.NET 2.0中操作數(shù)據(jù)之三十五:使用Repeater和DataList單頁面實(shí)現(xiàn)主/從報(bào)表
  • 在ASP.NET 2.0中操作數(shù)據(jù)之三十七:DataList批量更新
  • 在ASP.NET 2.0中操作數(shù)據(jù)之三十八:處理BLL和DAL的異常
  • 在ASP.NET 2.0中操作數(shù)據(jù)之三十九:在DataList的編輯界面里添加驗(yàn)證控件
  • 在ASP.NET 2.0中操作數(shù)據(jù)之四十:自定義DataList編輯界面
  • 在ASP.NET 2.0中操作數(shù)據(jù)之四十一:DataList和Repeater數(shù)據(jù)分頁
  • 在ASP.NET 2.0中操作數(shù)據(jù)之四十二:DataList和Repeater數(shù)據(jù)排序(一)
  • 在ASP.NET 2.0中操作數(shù)據(jù)之四十三:DataList和Repeater數(shù)據(jù)排序(二)

標(biāo)簽:玉林 喀什 泰安 ???/a> 德宏 房產(chǎn) 呂梁 佳木斯

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《在ASP.NET 2.0中操作數(shù)據(jù)之三十六:在DataList里編輯和刪除數(shù)據(jù)概述》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266