zoukankan      html  css  js  c++  java
  • 《ASP.NET1200例》在DataList里编辑和删除数据

    学习内容:如何创建一个支持编辑和删除数据的DataList。增加编辑和删除功能需要在DataList的ItemTemplate和EditItemTemplate里增加合适的控件,创建对应的事件处理,读取用户的输入和主键值,然后调用BLL来实现。

        使用GridView来编辑和删除数据之所以很简单,是因为GridView和ObjectDataSource在底层非常一致。当更新按钮被点击时,GridView自动将字段的值赋给ObjectDataSource的UpdateParameters集合,然后激发ObjectDataSource的Update()方法。而DataList与Repeater并没有相关使用方法。


        需要确保将合适的值赋给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 被点时激发.

        使用以上的属性和事件,有四种方法来更新和删除数据:(第一种方法提供了更好的可扩展性,而设计DataList的本意就是使用这种方式。)

        1. 使用ASP.NET 1.x 的技术— DataList先于ASP.NET 2.0 和ObjectDataSources 存在,可以直接通过编程来实现编辑和删除。这种方法需要在显示数据或者更新删除记录时,直接在BLL层将数据绑定到DataList。

        2. 使用一个单独的ObjectDataSource 来实现选择,更新和删除 — DataList没有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 使页面看起来混乱。

    注意:

    1. 当使用ObjectDataSource修改数据时,在声明标记里需要移除OldValuesParameterFormatString (或重新设为缺省值,{0})。在并发控制下可使用original_{0},表示原始数据。
     2. 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必须开启。
    3.默认DataList只有一个ItemTemplate。需要手动添加一个EditItemTemplate来支持编辑功能。
    4.DataList并不支持双向绑定,准备更新数据时,需要编程将Textbox的Text的值传给ProductsBLL类的UpdateProduct方法。

        当设置了CommandName的Repeater或DataList里的Button,LinkButton或ImageButton被点击时,Repeater或DataList的ItemCommand事件被激发。对DataList来说,如果CommandName设为某个值,另外一个事件也会被激发(除了ItemCommand被激发以外,下面事件也会激发),如下:

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

    【进入编辑功能】

    点击DataList里的button会引起postback,但是并没有进入product的编辑模式。为了完成这个,需要:
    1. 设置DataList的 EditItemIndex property 为 被点击了Edit button的 DataListItem的 index . 
    2. 重新绑定数据到 DataList. 当 DataList 重新展现时, 和DataList的EditItemIndex相关的DataListItem 会展现EditItemTemplate. 
    通过以下代码完成:
    C# 
    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;// EditItemIndex表示获取或设置 DataList 控件中要编辑的选定项的索引号。 
         // Rebind the data to the DataList
       DataList1.DataBind();
    }
        第二个参数类型为DataListCommandEventArgs ,它是被点击的Edit button的DataListItem的引用(e.Item).首先设置DataList的EditItemIndex为需要编辑的DataListItem的ItemIndex,然后重新绑定数据。使DataList以只读模式展示item,需要:
    1. 设置DataList的 EditItemIndex property 为一个不存在的DataListItem index -1是一个好的选择。(由于DataListItem index从0开始) 
    2. 重新绑定数据到DataList。由于没有DataListItem ItemIndex和DataList的EditItemIndex关联,整个DataList会展现为只读模式。

    可以通过以下代码完成:
    C# 
    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();
    }

    【实现更新功能】

    完成UpdateCommand event handler,需要:

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

    下面的代码完成了上面的功能:
    C# 
    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);//调用BLL中的重载方法
                // Revert the DataList back to its pre-editing state
    DataList1.EditItemIndex = -1;
    DataList1.DataBind();
    }

    【删除功能】

    为DataList的DeleteCommand事件创建一个event handler实现删除功能,见下面的代码:
    C# 
    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);//调用BLL中的方法
          // Rebind the data to the DataList
    DataList1.DataBind();
    }

        所有功能实现完成,本章结束。

        任务:关于BLL、DAL、ObjectDataSouce的层层调用,以及各自的参数传递问题,DataSet中的Adapter、DataTable直接的方法与查询,BLL中的函数重载问题,下次要做个专门的总结篇。

     
     
    自己编写的代码
    aspx
    <body>
        <form id="form1" runat="server">
        <div>
          <asp:DataList ID="DataList1" runat="server" Width="355px" 
                 DataKeyField="id" 
                oneditcommand="DataList1_EditCommand" onupdatecommand="DataList1_UpdateCommand"> 
    
             <HeaderTemplate>
                图片列表
             </HeaderTemplate>
    
             <SelectedItemStyle BackColor="Red">
             </SelectedItemStyle>
    
             <ItemTemplate>
               图片 <%# DataBinder.Eval(Container.DataItem, "id") %>
               <asp:LinkButton ID="LinkButton1"  Text="Detail" CommandName="Edit" runat="server">Edit</asp:LinkButton>
             </ItemTemplate>
    
             <EditItemTemplate>
                  图片ID  
                 <asp:TextBox ID="txtid" runat="server" Text='<%# Eval("id") %>'></asp:TextBox>
                  <br />
                  图片路径  
                 <asp:TextBox ID="txtimageUrl" runat="server" Text='<%# Eval("imageUrl") %>'></asp:TextBox>
                 <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Update">Save</asp:LinkButton>
             </EditItemTemplate>
    
          </asp:DataList>
    
        </div>
        </form>
    </body>
    View Code

    aspx.cs

     public partial class _236EditData : System.Web.UI.Page
        {
            ShowImageBll showImageBll = new BLL.ShowImageBll();
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindDataList();
                }
            }
    
            private void BindDataList()
            {
                DataSet ds = showImageBll.GetList();
                DataList1.DataSource = ds;
                DataList1.DataBind();
            }
            private void UpadteDataList(int id,String imageUrl)
            {
                showImageBll.UpdateList(id,imageUrl);
               
            }
    
            protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
            {
                DataList1.EditItemIndex  = e.Item.ItemIndex;
                BindDataList();
            }
    
            protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
            {
                // Read in the id from the DataKeys collection
                int id = int.Parse(DataList1.DataKeys[e .Item .ItemIndex ].ToString());
                string imageUrl = ((TextBox)e.Item.FindControl("txtimageUrl")).Text;// Read in the imageUr
                UpadteDataList(id, imageUrl); // Call the ShowImageBll's  UpadteDataLis method...
                Response.Write("<script>alert('更新成功!')</script>");
                DataList1.SelectedIndex = -1;// Revert the DataList back to its pre-editing state
                BindDataList();
                
            }
        }
    View Code

    【总结】:
    1.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 被点时激发.

    属性的名字必须设置为指定的Edit,Cancel ,Update,Delete

    2. 设置编辑事件 oneditcommand="DataList1_EditCommand" 后台编辑事件里面的代码如下:

    protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
            {
                DataList1.EditItemIndex  = e.Item.ItemIndex;
                BindDataList();
            }

     
     
     
  • 相关阅读:
    2020年3月15日python学习笔记——变量的创建过程 垃圾回收机制 变量的指向关系
    2020年3月14日python学习笔记——学习实操的程序(第一小章)--------------------重要
    2020年3月14日python学习笔记——break ,continue,while ...else....
    2020年3月14日python学习笔记——流程控制语句(if else ,while)
    2020年3月14日python学习笔记——算数运算、比较运算、逻辑运算、赋值运算
    2020年3月14日python学习笔记——列表 输入命令符
    Ubuntu 安装mysql和修改字符编码
    死锁与递归锁
    守护线程
    线程
  • 原文地址:https://www.cnblogs.com/abc8023/p/3453379.html
Copyright © 2011-2022 走看看