• ASP.NET 2.0数据教程之三十六 在DataList里编辑和删除数据


    导言


    概述插入、更新和删除数据 里我们已经学习了如何使用GridView等控件来插入,更新删除数据。通过ObjectDataSource和其它数据控件仅仅只需要在智能标签里勾一下checkbox就完成了,不需要写任何代码。

    而DataList没有这些内置的功能。我们可以使用1.x 里的方法来实现这些功能。在本章我们将看到,DataList提供了一些事件和属性来完成我们的目的,为此我们需要写一些代码。


    本章我们首先学习如何创建一个支持编辑和删除数据的DataList。后面的教程里我们将学习一些高级的编辑和删除方法,包括验证,DAL和BLL的异常处理等。

    注意:和DataList一样,Repeater也不提供内置的这些功能。而且Repeater里没有DataList里提供的那些事件和属性。因此本章和后面的几章我们仅仅只讨论DataList。

    第一步: 创建编辑和删除教程页

    首先创建本章和后面几章需要用到的页。添加一个名为EditDeleteDataList的文件夹。然后添加下面的页。确保每页都包含了Site.master。

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

    图 1: 添加页


    和别的文件夹一样,Default.aspx列出教程章节。记得SectionLevelTutorialListing.ascx用户控件提供了这个功能。从解决方案里将它拖到我们的页里。

    图 2: 添加SectionLevelTutorialListing.ascx 用户控件


    最后将这些页添加到Web.sitemap里。在Master/Detail Reports with the DataList and Repeater<siteMapNode>之后添加下面的标记:


    代码
    <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&apos;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&apos;s role or permissions."
    url
    ="~/EditDeleteDataList/UserLevelAccess.aspx" />
    </siteMapNode>
                

    更新了Web.sitemap后,浏览一下。

    图 3: 站点导航现在包含了编辑和删除DataList 教程

    第二步: 探讨更新和删除数据所要用到的技术


    使用GridView来编辑和删除数据之所以很简单,是因为GridView和ObjectDataSource在底层非常一致。如研究插入、更新和删除的关联事件里所讨论的,当更新按钮被点击时,GridView自动将字段的值赋给ObjectDataSource的UpdateParameters集合,然后激发ObjectDataSource的Update()方法。

    我们现在需要确保将合适的值赋给ObjectDataSource的参数,然后调用Update()方法。DataList提供了以下的属性和事件来帮助我们完成这些:

    •  DataKeyField property — 更新或删除时,我们需要唯一确定DataList里的每个item。将这个属性设为显示的数据的主健。这样做会产生DataList的 DataKeys collection ,每个item都有一个指定的 DataKeyField .
    •  EditCommand event — 当CommandName属性设为“Edit”的Button, LinkButton, 或 ImageButton 被点时激发.
    •  CancelCommand event — 当CommandName属性设为“Cancel”的Button, LinkButton, 或 ImageButton 被点时激发.
    •  UpdateCommand event — 当CommandName属性设为“Update”的Button, LinkButton, 或 ImageButton 被点时激发.
    •  DeleteCommand event — 当CommandName属性设为“Delete”的Button, LinkButton, 或 ImageButton 被点时激发.


    使用以上的属性和事件,我们有四种方法来更新和删除数据:

    1. 使用ASP.NET 1.x 的技术— DataList先于ASP.NET 2.0 和ObjectDataSources 存在,可以直接通过编程来实现编辑和删除。这种方法需要我们在显示数据或者更新删除记录时,直接在BLL层将数据绑定到DataList。
    2. 使用一个单独的ObjectDataSource 来实现选择,更新和删除 — DataList没有GridView内置的编辑删除功能,并不意味着我们不能添加这些功能。我们象在GridView的例子里那样,使用 ObjectDataSource,但是在设置ObjectDataSource的参数并调用Update()方法时,需要为DataList的UpdateCommand事件创建一个  event handler。
    3. Using an ObjectDataSource Control for Selecting, but Updating and Deleting Directly Against the BLL — 使用第二种方法时我们需要为UpdateCommand事件和参数赋值等写一些代码。其实我们可以用ObjectDataSource来实现selecting ,更新和删除直接调用BLL(象第一种方法)。我的意见是,直接调用BLL会使代码可读性更好。
    4. 使用多个ObjectDataSources —前面的三种方法都需要一些代码。如果你宁愿坚持使用尽可能多的声明语法的话,最后一种方法是使用多个ObjectDataSources 。第一个ObjectDataSource 从BLL获取数据,并绑定到 DataList. 为更新添加另一个 ObjectDataSource, 直接添加到 DataList的 EditItemTemplate.同样对删除也是如此。三个 ObjectDataSource通过 ControlParameters   声明语法直接将参数绑定到ObjectDataSource 的参数 (而不是在 DataList的 UpdateCommand event handler编程处理). 这种方法也需要一些编码 — 我们需要调用 ObjectDataSource内置的 Update() 或 Delete() — 但是比起其它三种方法,代码少的多。这种方法的劣势是多个  ObjectDataSources 使页面看起来混乱。

    我喜欢选择第一种方法,因为它提供了更好的可扩展性,而设计DataList的本意就是使用这种方式。当扩展DataList使它和ASP.NET 2.0的数据源控件一起工作时,它没有“正式”的ASP.NET 2.0数据控件( GridView, DetailsView, 和FormView)的那些可扩展性或特性。当然其它方法也不是没有优点。

    这几章关于编辑和删除的教程会使用ObjectDataSource 来显示数据,然后直接调用BLL来实现编辑和删除(第三种方法)

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


    本章我们将创建一个DataList用来列出product的信息,并提供用户编辑其name和price,删除的功能。我们使用ObjectDataSource来显示数据,调用BLL来实现更新和删除的功能。首先我们来实现一个只读的显示product的页。由于在前面的教程里已经实现过这样的功能,在这里我们很快带过。

    打开EditDeleteDataList文件夹下的Basics.aspx页,添加一个DataList。然后通过智能标签创建一个ObjectDataSource。在SELECT标签里使用ProductsBLL类的GetProducts()方法配置它。

    图 4: 使用ProductBLL类配置ObjectDataSource

    图 5: 选择GetProducts()


    在INSERT,UPDATE和DELETE标签里都选择None。

    图 6: 在INSERT, UPDATE, 和DELETE 标签里选择(None)


    完成配置后回到设计界面。如我们在以前的例子里看到的那样,Visual Studio 会自动创建ItemTemplate,显示数据。将ItemTemplate改为只显示product的name和price。然后将RepeatColumns设为2。

    注意:象以前讨论的那样,当使用ObjectDataSource修改数据时,我们在声明标记里需要移除OldValuesParameterFormatString (或重新设为缺省值,{0})。而本章ObjectDataSource仅仅只用来获取数据,因此不需要那样做(当然那样做了也没关系)。

    完成后你的页代码看起来应该和下面差不多:

    代码
    <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里。因此创建支持编辑和删除功能的DataList时,DataList的view state需要开启。


    聪明的读者应该记起来在创建可编辑的GridView,DetailsViews和FormViews的时候,view state是禁用的。这是因为ASP.NET 2.0 控件包含了control state,它在postback时状态是连续的。


    在GridView里禁用了view state仅仅只是忽略了无关紧要的状态信息,但是维持了control state(它包含了编辑和删除需要的状态)。而DataList是 ASP.NET 1.x时代创建的,并没有使用control state,因此view state必须开启。更多的control state的目的以及和view state的区别信息见Control State vs. View State

    第四步: 添加一个编辑界面


    GridView控件是由字段集合组成的(BoundFields, CheckBoxFields, TemplateFields等)。这些字段能根据模式来调整标记。比如,在只读模式下,BoundField 将字段值显示为文本,而在编辑模式下,它将显示为一个TextBox,这个TextBox的Text属性被赋予字段的值。

    另一方面,DataList用template来展现它的item。只读的item用ItemTemplate来展现。而当在编辑模式下时,item用EditItemTemplate来展示。现在我们的DataList只有一个ItemTemplate。我们需要添加一个EditItemTemplate来支持编辑功能。本章我们使用TextBox来编辑product的name和price。

    可以通过声明语言或设计视图(DataList的智能标签的EditTemplate选项)来创建EditItemTemplate。

    图 8:选择EditItemTemplate


    然后输入“Product name:” 和“Price:” ,再拖两个TextBox到EditItemTemplate。将TextBox的ID属性设为ProductName和UnitPrice。

    图 9:  添加TextBox


    我们需要将product的字段绑定到关联的TextBox。在TextBox的智能标签上点击Edit DataBindings,然后将Text属性和适当的字段关联。见图10。


    注意:将UnitPrice绑定到TextBox时,你可以用({0:C})将它 格式化为货币值,或用({0:N})表示为普通数字,或者不格式化。

    图 10:绑定字段到TextBoxes


    注意:图10里的Edit DataBindings对话框里并不包含“双向数据绑定”的checkbox,而在编辑GridView或DetailsVIew里的TemplateField,或者FormView里的template里时是有这个checkbox的。双向数据绑定允许在插入或更新数据时,输入控件的值自动赋给相关联的ObjectDataSource的InsertParameters或UpdateParameters。DataList并不支持双向绑定—我们在后面会看到,在用户作出更改,准备更新数据时,我们需要编程将Textbox的Text的值传给ProductsBLL类的UpdateProduct方法。


    最后我们在EditItemTemplate里加入Update和Cancel按钮。象前面看到的那样,当设置了CommandName的Repeater或DataList里的Button,LinkButton或ImageButton被点击时,Repeater或DataList的ItemCommand事件被激发。对DataList来说,如果CommandName设为某个值,另外一个事件也会被激发,如下:

    • “Cancel” — 激发 CancelCommand event
    • “Edit” — 激发 EditCommand event
    • “Update” — 激发UpdateCommand event


    记住除了ItemCommand外,这些事件会激发。


    为EditItemTemplate添加两个Button,一个CommandName设为"Update",一个设为"Cancel"。完成后,设计界面看起来应该和下面差不多:

    图 11: 为 EditItemTemplate 添加Update 和Cancel 按钮


    你的标记语言看起来应该和下面差不多:

    代码
    <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" />&nbsp;
            
    <asp:Button ID="CancelUpdate" runat="server" CommandName="Cancel" Text="Cancel" />
        
    </EditItemTemplate>
    </asp:DataList>


     

    第五步: 添加进入编辑模式的入口


    现在我们的DataList有一个编辑界面了。然而现在还没有办法来体现出用户需要编辑product信息。我们需要为每个product加一个Edit button,当点击时,将DataList item展示为编辑模式。同样的可以通过设计器或直接声明代码来添加。确保将Edit button的commandName属性设为"Edit".

    添加完后,浏览一下页面。

    图 12: 添加Edit Buttons


    点击button会引起postback,但是并没有进入product的编辑模式。为了完成这个,我们需要:

    1. 设置DataList的 EditItemIndex property 为 被点击了Edit button的 DataListItem的 index .
    2. 重新绑定数据到 DataList. 当 DataList 重新展现时, 和DataList的EditItemIndex相关的DataListItem 会展现EditItemTemplate.


    由于在点Edit button时,DataList的EditCommand事件被激发,使用下面的代码创建一个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 的第二个参数类型为DataListCommandEventArgs ,它是被点击的Edit button的DataListItem的引用(e.Item).首先设置DataList的EditItemIndex为想编辑的DataListItem的ItemIndex,然后重新绑定数据。

    完成后再浏览页面。点Edit button,现在product变成了可编辑的。见图13。

    图 13: 点Edit Button 使Product 可编辑

    第六步: 保存用户的更改


    现在点product的Update或Cancel button不会有任何反应。为了完成目标我们需要为DataList的UpdateCommand和CancelCommand创建event handler。首先创建CancelCommand event handler,它在product的Cancel button点击时执行,使DataList返回编辑之前的状态。

    使DataList以只读模式展示item,我们需要:

    1. 设置DataList的 EditItemIndex property 为一个不存在的DataListItem index -1是一个好的选择。(由于DataListItem index从0开始)
    2. 重新绑定数据到DataList。由于没有DataListItem ItemIndex和DataList的EditItemIndex关联,整个DataList会展现为只读模式。


    这些可以通过以下代码完成:

    代码
    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();
    }

    现在点击Cancel button会返回到DataList编辑前的状态。

    最后我们来完成UpdateCommand event handler,我们需要:

    1. 编程获取用户输入的product name和price,还有ProductID.
    2. 调用ProductsBLL类里的合适的UpdateProduct重载方法.
    3. 设置DataList的EditItemIndex property 为一个不存在的DataListItem index. -1 是一个好的选择。
    4. 重新帮顶数据。


    第一和第二步负责保存用户的更改。第三步返回到DataList编辑前的状态(和CancelCommand event handler一样)。


    我们需要使用FindControl方法来获取product的name和price(当然包括ProductID)。当最初将ObjectDataSource绑定到DataList时,Visual Studio 将DataList的DataKeyField 属性赋为数据源的主键值(ProductID)。这个值可以通过DataList的DataKey集合来获取。花点时间验证一下DataKeyField 是否设置为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。然后将两个TextBox的Text属性存起来。我们用Decimal.Parse() 方法去读UnitPrice TextBox的值,以便在这个值有货币符号时可以正确的转换。


    注意:只有在TextBox的Text指定了值的情况下,productNameValue和unitPriceValue变量才会被赋值。否则,会在更新数据时使用一个NULL值。也就是说我们的代码会将空字符串转换为NULL值,而在GridView,DetailsView和FormView控件的编辑界面里NULL是缺省值。


    获取值后,调用ProductsBLL类的UpdateProduct方法,将product的name,price和ProductID传进去。使用和CancelCommand event handler里同样的逻辑返回到DataList编辑前状态。


    完成了EditCommand,CancelCommand和UpdateCommand event handler后,用户可以编辑product的name和price了。见图14。

    图 14: 浏览页时所有的Products都是只读模式

    图 15: 点击Edit Button

    图 16: 改变值后,点击 Update返回只读模式

    第七步: 增加删除功能


    增加删除功能的步骤和增加编辑功能差不多。简单来说我们需要在ItemTemplate里添加一个Delete button,当点击时:

    1. DataKeys 集合里读取关联的proudct的ProductID .
    2. 调用ProductsBLL class的DeleteProduct 方法执行删除操作.
    3. 重新绑定数据到 DataList.

    首先来增加一个Delete button.

    当点击一个CommandName为“Edit”, “Update”, 或“Cancel”的Button时,会激发DataList的ItemCommand事件和另外一个事件(比如,使用“Edit”时EditCommand 事件会被激发)。同样的,CommandName为“Delete”时会激发DeleteCommand 事件(和ItemCommand一起)。


    在Edit button后面增加一个Delete button ,将CommandName属性设为“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" />
    &nbsp;
    <asp:Button runat="server" id="DeleteProduct" CommandName="Delete" Text="Delete" />
    <br />
    <br />
    </ItemTemplate>

    然后为DataList的DeleteCommand事件创建一个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();
    }

    点击Delete button 会引起postback,并激发DataList的DeleteCommand事件。在事件处理中,被点击的product的ProductID的值通过DateKeys集合来获取。然后,调用ProductsBLL类的DeleteProduct方法来删除product。


    删除product后,要将数据重新绑定到DataList(DataList1.DataBind()),否则DataList里还会看到刚才删除的product。

    总结


    通过少量的代码,DataList也可以拥有GridView的编辑删除功能。在本章我们学习了如何创建一个两列的显示product的页,并且可以编辑name和price,删除product。增加编辑和删除功能需要在ItemTemplate和EditItemTemplate里增加合适的控件,创建对应的事件处理,读取用户的输入和主键值,然后调用BLL。

    虽然我们为DataList增加了基本的编辑和删除功能,它还是缺少一些高级特性。比如,没有输入字段验证- 如果用户输入的price太“贵”,Decimal.Parse在转换为Decimal时会抛出异常。同样的,如果在更新数据时,BLL或DAL里有异常,用户会看到系统错误。在删除时没有任何确认,很可能会误删数据。

  • 相关阅读:
    Moment.js 超棒Javascript日期处理类库
    java模拟http/https post请求
    Mysql中int和varchar类型
    ssh免密码登录
    Linux优雅退出问题
    Jenkins的权限控制和Rundeck的远程认证
    Jenkins系统+独立部署系统
    Nginx基本介绍
    初窥项目构建
    Rundeck概况
  • 原文地址:https://www.cnblogs.com/Fskjb/p/1727451.html
Copyright © 2020-2023  润新知