欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

程序员文章站 2023-12-18 09:47:40
导言   结束前面的几节,我们已经探讨过了如何使用gridview、detailsview和formview控件来显示数据。这些控件简单地操作提供给它的数据。一般地,这些...

导言

  结束前面的几节,我们已经探讨过了如何使用gridview、detailsview和formview控件来显示数据。这些控件简单地操作提供给它的数据。一般地,这些控件通过使用一个数据源控件,例如objectdatasource来存取数据。我们已经看过了objectdatasource是如何在asp.net页面和潜在的数据之间扮演一个代理的角色。当一个gridview需要显示数据时,它调用objectdatasource的select()方法,这个方法转而调用一个来自我们的业务逻辑层(bll)的方法,继而调用一个适当的数据访问层(dal)的表适配器(tableadapter)的方法,从而它发送一个select查询到northwind数据库。

  记得在我们的教程里当创建dal中的表适配器时,visual studio自动地添加从潜在数据库插入、更新和删除数据的方法。此外,在创建一个业务逻辑层这一节我们已经设计了调用这些数据更改的dal方法的bll方法。
除了它的select()方法,objectdatasource还有insert()、update()和delete()方法。跟select()方法类似,这三个方法映射到一个隐含的对象。当配置插入、更新或删除数据时,gridview、detailsview和formview控件提供了一个修改潜在的数据的用户界面。这个用户界面调用objectdatasource的insert()、update()和delete()方法,它们继而调用隐含对象的关联方法(见图1)。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 1: objectdatasource的insert()、update()和delete()方法提供一个到bll的代理

  本节我们将看看如何映射objectdatasource的insert()、update()和delete()方法到bll中的类,也看看如何配置gridview、detailsview和formview控件提供修改数据的功能。

第一步: 创建insert、update和delete教程页面

  在我们开始探讨如何插入、修改和删除数据之前,让我们先花些时间在我们的站点项目里添加这些本节里和下一节里需要的asp.net页面。首先添加一个名为editinsertdelete的新文件夹。然后,在这个文件夹里添加下面这些asp.net页面,并且确认每个页面都关联site.master母版页:

·default.aspx
·basics.aspx
·datamodificationevents.aspx
·errorhandling.aspx
·uivalidation.aspx
·customizedui.aspx
·optimisticconcurrency.aspx
·confirmationondelete.aspx
·userlevelaccess.aspx

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 2: 添加这些与数据更改关联的教程的页面

  类似在其它文件夹里,editinsertdelete文件夹里的default.aspx将列出这些教程章节。记得用户控件提供这个功能。因此,从解决方案资源管理器中拖拽一个这个用户控件到页面的设计视图,从而添加它到default.aspx页面。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 3: 添加sectionleveltutoriallisting.ascx用户控件到tdefault.aspx页面

  最后,添加这些页面地址项到web.sitemap文件。明确地,在customized formatting <sitemapnode>后添加如下标记:

<sitemapnode title="editing, inserting, and deleting"
  url="~/editinsertdelete/default.aspx"
  description="samples of reports that provide editing, inserting,
         and deleting capabilities">
  <sitemapnode url="~/editinsertdelete/basics.aspx"
    title="basics"
    description="examines the basics of data modification with the
           gridview, detailsview, and formview controls." />
  <sitemapnode url="~/editinsertdelete/datamodificationevents.aspx"
    title="data modification events"
    description="explores the events raised by the objectdatasource
           pertinent to data modification." />
  <sitemapnode url="~/editinsertdelete/errorhandling.aspx"
    title="error handling"
    description="learn how to gracefully handle exceptions raised
           during the data modification workflow." />
  <sitemapnode url="~/editinsertdelete/uivalidation.aspx"
    title="adding data entry validation"
    description="help prevent data entry errors by providing validation." />
  <sitemapnode url="~/editinsertdelete/customizedui.aspx"
    title="customize the user interface"
    description="customize the editing and inserting user interfaces." />
  <sitemapnode url="~/editinsertdelete/optimisticconcurrency.aspx"
    title="optimistic concurrency"
    description="learn how to help prevent simultaneous users from
           overwritting one another s changes." />
  <sitemapnode url="~/editinsertdelete/confirmationondelete.aspx"
    title="confirm on delete"
    description="prompt a user for confirmation when deleting a record." />
  <sitemapnode url="~/editinsertdelete/userlevelaccess.aspx"
    title="limit capabilities based on user"
    description="learn how to limit the data modification functionality
           based on the user role or permissions." />
</sitemapnode>

在更新了web.sitemap后,花些时间通过浏览器访问本教程站点。左边的菜单里现在包含对应编辑、插入和删除教程的项。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 4: 站点地图现在包含了对应编辑、插入和删除教程的项

第二步: 添加并配置objectdatasource控件

  因为gridview、detailsview和formview控件在数据修改功能和版面上都有所不同,就让我们逐个研究。不过,与其让这三个控件各自使用自己的objectdatasource,还不如让我们仅创建一个objectdatasource让这个三个控件的例子共用。
打开basics.aspx页面,从工具箱拖拽一个objectdatasource到设计器,从它的职能标记中点击配置数据源链接。因为productsbll类是唯一一个提供修改、插入和删除方法的bll类,配置该objectdatasource使用这个类。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 5: 配置objectdatasource使用productsbll类

  在下一屏中,通过选择适当的tab页并从下拉列表中选择方法,我们可以指定productsbll类里的哪些方法被映射到objectdatasource的select()、insert()、update()和delete()方法。图6,至今我们应该很熟悉,映射objectdatasource的select()方法到productsbll类的getproducts()方法。insert()、update()和delete()方法可以通过选择上方的适当的tab页进行配置。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 6: 让这个objectdatasource返回所有产品

  图7、8和9显示objectdatasource的update、insert,和delete 的tab页。配置它们从而insert()、update()和delete()方法分别调用productsbll类的updateproduct、addproduct和deleteproduct方法。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 7: 映射objectdatasource的update()方法到productbll类的updateproduct方法

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 8: 映射objectdatasource的insert()方法到productbll类的addproduct方法

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 9: 映射objectdatasource的delete()方法到productbll类的deleteproduct方法

  你也许已经注意到在update、insert和delete的tab页里的下拉列表中已经选择了各自的方法。这是由于我们使用了dataobjectmethodattribute,它修饰了producstbll类。例如,deleteproduct方法是如下这样子声明的:

[system.componentmodel.dataobjectmethodattribute
  (system.componentmodel.dataobjectmethodtype.delete, true)]
public bool deleteproduct(int productid)
{
  ...
}

dataobjectmethodattribute指示每一个方法的目的–是否为了查询、插入、更新或删除–

是否它的默认值。如果你在创建bll类的时候省略了这些属性,现在你将需要手工从update、insert和delete的tab页里手工选择方法。

当确认已经适当的productsbll方法映射到objectdatasource的insert()、update()和delete()方法后,点击完成结束此向导。
检查objectdatasource的标记

在通过数据源配置向导完成了对objectdatasource的配置之后,到源视图去检查一下生成的声明标记。

<asp:objectdatasource>标签列明了隐含的对象和需要调用的方法。另外,还有deleteparameters、updateparameters和insertparameters ,它们映射productsbll类的addproduct、updateproduct和deleteproduct方法的输入参数:

<asp:objectdatasource id="objectdatasource1" runat="server"
  deletemethod="deleteproduct" insertmethod="addproduct"
  oldvaluesparameterformatstring="original_{0}" selectmethod="getproducts"
  typename="productsbll" updatemethod="updateproduct">
  <deleteparameters>
    <asp:parameter name="productid" type="int32" />
  </deleteparameters>
  <updateparameters>
    <asp:parameter name="productname" type="string" />
    <asp:parameter name="supplierid" type="int32" />
    <asp:parameter name="categoryid" type="int32" />
    <asp:parameter name="quantityperunit" type="string" />
    <asp:parameter name="unitprice" type="decimal" />
    <asp:parameter name="unitsinstock" type="int16" />
    <asp:parameter name="unitsonorder" type="int16" />
    <asp:parameter name="reorderlevel" type="int16" />
    <asp:parameter name="discontinued" type="boolean" />
    <asp:parameter name="productid" type="int32" />
  </updateparameters>
  <insertparameters>
    <asp:parameter name="productname" type="string" />
    <asp:parameter name="supplierid" type="int32" />
    <asp:parameter name="categoryid" type="int32" />
    <asp:parameter name="quantityperunit" type="string" />
    <asp:parameter name="unitprice" type="decimal" />
    <asp:parameter name="unitsinstock" type="int16" />
    <asp:parameter name="unitsonorder" type="int16" />
    <asp:parameter name="reorderlevel" type="int16" />
    <asp:parameter name="discontinued" type="boolean" />
  </insertparameters>
</asp:objectdatasource>

  objectdatasource包含了对应它关联的方法的每一个输入参数的parameter,就像当objectdatasource被配置为调用预期一个输入参数的查询方法(例如getproductsbycategoryid(categoryid))时出现的selectparameters一栏。正如我们马上即将看到的,这些deleteparameters、updateparameters和insertparameters的值在调用objectdatasource的insert()、update()或delete()方法之前自动地通过gridview、detailsview和formview被设置。必要时这些值也可以通过编程设置,这在以后的章节里讨论。

  使用数据源配置向导来配置objectdatasource的另一个影响是visual studio设置了oldvaluesparameterformatstring属性为original_{0}。这个属性值用来包含数据被编辑时的原始值,它在下面两种情况下非常有用:

·如果,当编辑一条记录时,用户可以修改主键的值。在这种情况下,新的主键的值和原始的主键值都需要提供,这样具有这个原始主键值的数据库记录才可以被找到然后才能将它的值更新。

·当使用开放式并发。开放式并发是为了保证同时操作的用户不至于覆盖另一个用户所做更改的一种技巧,这也是后面的教程中的一节(实现开放式并发 )。

  这个oldvaluesparameterformatstring属性指明了隐含对象的更新和删除方法中对应原始值的输入参数的名称。我们将在探讨开发式并发的时候更详细地讨论这个属性和它的目的。不过暂时我放下它,因为我们的bll的方法并不需要这些原始的值因此我们删除这个属性,这一点很重要。如果让oldvaluesparameterformatstring属性设置为除了默认值({0})以外的其它任何的值,都将在数据web控件尝试调用objectdatasource的update()或delete()方法时引发一个错误,因为objectdatasource将尝试将这些原始值参数与updateparameters或deleteparameters一起传入。

  如果对此不是十分清楚,别担心,我们将在未来的章节中研究这个属性和它的效用。暂时,一定要完全地从声明语法中完全地删除这个属性或者将它设置为默认值({0})。

  注意: 如果你只是简单地从设计视图的属性窗口删除这个oldvaluesparameterformatstring属性的值,这个属性依旧会存在于声明语法中,不过被设置为一个空字符串。不幸地,这将依旧导致上面提到的同样的问题。所以,从声明语法里彻底地删除这个属性,或者从属性窗口将其设置为默认值,{0}。

第三步: 添加一个数据web服务器控件并配置它为数据更改服务

  一般objectdatasource被添加到页面并配置完成,我们可以添加一个数据web服务器控件用来显示数据并提供一个最终用户修改数据的途径。我们将分别看看gridview、detailsview和formview,因为这些数据web服务器控件在它们的数据更改功能和配置上都有所不同。

  正如我们将在本文剩下的部分里看到的,通过gridview、detailsview和formview控件添加一个非常基本的编辑、插入和删除支持是真的非常简单,只需要勾选上一对checkbox。现实中提供这样的功能有许多微妙之处和边缘案例,这要比仅仅点几下要棘手得多。但是,本教程里,只着眼于提供简单的数据修改功能。以后的章节将研究在现实中不容置疑地出现的问题。

从gridview中删除数据

  首先,从工具箱拖拽一个gridview到设计器。然后,通过gridview的智能标记中从下拉列表中选择从而绑定objectdatasource到该gridview。在这里gridview的声明标记将是:

<asp:gridview id="gridview1" runat="server" autogeneratecolumns="false"
  datakeynames="productid" datasourceid="objectdatasource1">
  <columns>
    <asp:boundfield datafield="productid" headertext="productid"
      insertvisible="false"
      readonly="true" sortexpression="productid" />
    <asp:boundfield datafield="productname" headertext="productname"
      sortexpression="productname" />
    <asp:boundfield datafield="supplierid" headertext="supplierid"
      sortexpression="supplierid" />
    <asp:boundfield datafield="categoryid" headertext="categoryid"
      sortexpression="categoryid" />
    <asp:boundfield datafield="quantityperunit"
      headertext="quantityperunit"
      sortexpression="quantityperunit" />
    <asp:boundfield datafield="unitprice" headertext="unitprice"
      sortexpression="unitprice" />
    <asp:boundfield datafield="unitsinstock"
      headertext="unitsinstock" sortexpression="unitsinstock" />
    <asp:boundfield datafield="unitsonorder"
      headertext="unitsonorder" sortexpression="unitsonorder" />
    <asp:boundfield datafield="reorderlevel"
      headertext="reorderlevel" sortexpression="reorderlevel" />
    <asp:checkboxfield datafield="discontinued"
      headertext="discontinued" sortexpression="discontinued" />
    <asp:boundfield datafield="categoryname"
      headertext="categoryname" readonly="true"
      sortexpression="categoryname" />
    <asp:boundfield datafield="suppliername"
      headertext="suppliername" readonly="true"
      sortexpression="suppliername" />
  </columns>
</asp:gridview>

通过它的职能标记绑定gridview到objectdatasource有下面两点的好处:

·绑定列和checkbox列被自动地添加,对应objectdatasource返回的每一个字段。而且,这些绑定列和checkbox列的属性已经被设置,基于隐含字段的元数据。例如productid、categoryname和suppliername列在productsdatatable里被标记为只读,因此它们在编辑时也是不可更新的。为了实现这一点,这些绑定列的readonly属性设置为true 。

·datakeynames属性被赋值为隐含对象的主键。这是在使用gridview来编辑或删除数据的要点,因为这个属性象指出了标识唯一记录的那个字段(或是一组字段)。如果要获得更多的关于datakeynames属性的信息,请回到使用gridview 和detailview实现的主/从报表一节。

虽然可以通过属性窗口或者声明语法将gridview绑定到objectdatasource,不过这需要你手工添加适当的绑定列和datakeynames标记。

gridview控件提供了对行编辑和删除的内建的支持。配置一个gridview支持删除需要添加一个删除按钮列。当最终用户点击某一特定行的删除按钮时,引发一次回传并且gridview执行以下步骤:

1.对objectdatasource的deleteparameters赋值
2.调用objectdatasource的delete()方法,删除指定的记录
3.通过调用它的select()方法gridview重新绑定到objectdatasource

赋值到deleteparameters的值是点击删除按钮这一行的datakeynames字段的值。因此正确地设置gridview的datakeynames属性是至关重要的。如果缺少了这个,deleteparameters将在第1步被赋上一个null值,从而在第2步中将不会导致删除任何记录。

为了给gridview增加删除功能,简单地到它的职能标记里勾选上“启用删除”。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 10: 勾选“启用删除”

从智能标记中勾选启用删除会添加一个commandfield到gridview。这个commandfield在gridview中补充一个按钮列,它履行一个或多个下属任务:选中一行记录、编辑一行记录和删除一行记录。我们先前在使用gridview 和detailview实现的主/从报表一节的教程里也看到过了commandfield用作选中记录时如何运作。

这个commandfield包含了一些showxbutton属性,它指示哪一系列的按钮显示在commandfield中。通过勾选启用删除,一个showdeletebutton属性为true的commandfield被添加到gridview的列集合。

<asp:gridview id="gridview1" runat="server" autogeneratecolumns="false"
  datakeynames="productid" datasourceid="objectdatasource1">
  <columns>
    <asp:commandfield showdeletebutton="true" />
    ... boundfields removed for brevity ...
  </columns>
</asp:gridview>

到这里,你可能还不能相信,我们已经完成了给这个gridview增加删除支持!正如图11显示的,当我们通过浏览器访问此页面时,一列删除按钮已经出现。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 11: 这个commandfield添加一列删除按钮

  如果你是从一开始就是自己创建本教程的程序,当测试这个页面点击删除按钮时将引发一个异常。继续读下去学习关于为什么会引发这些异常,还有如何修复它们。
  注意: 如果你是跟随着下载的教程的程序,这些问题已经被解决。然而,我鼓励你从头到尾读一遍下面列出的详细资料来帮助你识别可能出现的问题和适宜的工作区。
  如果,当尝试删除一个产品,你得到一个类似于“objectdatasource 'objectdatasource1' could not find a non-generic method 'deleteproduct' that has parameters: productid, original_productid,”的异常,你可能忘记了从objectdatasource里删除oldvaluesparameterformatstring属性。指定了oldvaluesparameterformatstring属性的话,该objectdatasource会试图向deleteproduct方法一并传入productid和original_productid输入参数,然而,deleteproduct方法只能接受一个输入参数,导致异常。删除oldvaluesparameterformatstring属性(或设置它为{0})指示objectdatasource不要试图传入这个原始值的输入参数。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 12: 确保oldvaluesparameterformatstring属性已被彻底清除

  即使你已经删除了oldvaluesparameterformatstring属性,当你尝试删除一个产品时依旧将得到一个异常:“the delete statement conflicted with the reference constraint 'fk_order_details_products'.”。northwind数据库包含了一个在order details和products表间的字段约束,表示如果一个产品在order details表里对应它有一条或多条记录,那么该产品不能被删除。因为northwind数据库里的每一个产品在order details表里都至少有一条记录,所以我们不能删除任何产品,除非我们从order details表里删除这个产品的关联记录。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 13: 一个字段间约束阻止了对产品的删除

为了我们的教程,就让我们删除order details表里的所有记录吧。在一个真实的应用程序中我们需要的是下面任一措施:
·通过另外一个页面管理order details信息
·在deleteproduct方法里增加包含删除指定产品的订单明细的逻辑
·修改tableadapter所使用的sql语句,包含对指定产品的订单明细的删除
就让我们从order details表里删除所有记录从而绕过字段间约束的问题。到visual studio的服务器资源管理器,在northwnd.mdf节点上点击鼠标右键,选择“新建查询”。然后,再查询窗口执行下面的sql语句:delete from [order details]

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 14: 从order details表里删除所有记录

  在清空了order details表后,点击删除按钮将会正确无误地删除这个产品。如果点击了删除按钮但是没有删除该产品,检查并确保gridview的datakeynames属性设置为主键(productid)。

  注意:当点击删除按钮时引发一次回传并删了了该记录。这是危险的,因为它很容易意外地错误点击了别的行的删除按钮。以后的章节里我们将看看如何在删除记录时添加一个客户端的确认询问。

在gridview中编辑数据

  跟删除支持一起,gridview还提供了内建的对行编辑的支持。配置grdiview支持编辑将添加一列编辑按钮。从最终用户的角度,点击一行的编辑按钮可使这一行变成可编辑的,它的单元格转换成文本框并包含现有的值,并把编辑按钮替换成保存和取消按钮。在完成了他们期望的更改之后,最终用户可以点击保存按钮提交这些修改,或者点击取消按钮放弃这些修改。在任意一种情况,点击保存或者取消按钮后gridview回到它编辑前的状态。

站在我们页面开发者的角度,当最终用户点击特定一行的编辑按钮时,引发一次回传并且gridview执行以下步骤:

1.gridview的edititemindex属性被赋值为当前点击编辑按钮的行的索引
2.通过调用它的select()方法,gridview重新绑定自己到objectdatasource
3.与edititemindex相匹配的行呈现为编辑模式。在此模式下,编辑按钮替换为保存和取消按钮,并且那些readonly属性为false的绑定列呈现为textbox服务器控件,这些textbox的text属性被赋值为相应的数据字段的值。

到这里html标记被返回到浏览器,允许最终用户可以修改行数据。当用户点击保存按钮,再次发生一次回传,并且gridview执

行以下几个步骤:

1.objectdatasource的updateparameters的值被赋值为最终用户在gridview的编辑界面输入的值
2.调用objectdatasource的update()方法,更新指定的记录
3.通过调用它的select()方法,gridview重新绑定自己到objectdatasource

  在datakeynames属性指定的主键的值在第1步中赋值到updateparameters,反之非主键的值来自当前编辑行的textbox服务器控件。如果这一点遗漏了,那么updateparameters主键的值在第1步中将被赋上一个值,然后转入第2步中将不会导致任何记录的更新。

  编辑功能可以简单地通过勾选gridview的智能标记中的启用编辑从而被激活。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 15: 勾选启用编辑

  勾选启用编辑将添加一个commandfield(如果需要的话)并设置它的showeditbutton属性为true 。如我们之前所看过的,commandfield包含一些showxbutton属性,他们指出哪一系列的按钮要显示在commandfield里。在我们的例子里,勾选启用编辑添加showeditbutton属性到现有的commandfield里:

<asp:gridview id="gridview1" runat="server" autogeneratecolumns="false"
  datakeynames="productid" datasourceid="objectdatasource1">
  <columns>
    <asp:commandfield showdeletebutton="true"
      showeditbutton="true" />
    ... boundfields removed for brevity ...
  </columns>
</asp:gridview>

就这样就添加了根本的编辑支持。如图16所示,编辑界面还比较粗糙–每一个非只读的绑定列呈现为一个textbox。这包括像categoryid和supplierid的字段,而它们是来自其它表的外键。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 16: 点击产品“chai”的编辑按钮让此行显示为“编辑模式”

为了要求用户直接编辑外键,这个编辑界面还缺少了以下途径:

·如果用户输入一个在数据库中不存在的categoryid或supplierid,此更新将违反一个字段间的约束,引发一个异常。

·这个编辑界面不包含任何数据验证。如果你不提供一个必填的值(例如productname),或者在要求输入数字的地方输入一个字符串,将抛出一个异常。未来的章节里将研究如何在编辑的用户界面中增加验证控件(给编辑和新增界面增加验证控件)。

·通常,产品的所有非只读字段都必须包含在gridview里。如果我们从gridview里剔除一列,比如说unitprice,当更新数据时gridview将不会设置unitprice updateparameters的值,这将把该数据库记录的unitprice值更改为null值。类似地,如果一个必填的字段,例如productname,从gridview中被剔除了,那么这个更新将失败,并出现一个上文中提及过的“column 'productname' does not allow nulls”异常。

·这个编辑界面遗留了许多必要的格式化的问题。unitprice显示为四位小数。理想地categoryid和supplierid应该包含下拉列表(dropdownlist),它列出系统中存在的类别和供应商。

我们不得不承认现在这还有许多缺点,但这些将在未来的章节里谈及。

在detailsview中插入、编辑和删除数据

  正如我们在之前的章节里看过的,detailsview控件一次只显示一条记录,就像gridview一样,它也允许对当前显示的记录进行编辑和删除。不管是对最终用户来说从detailsview进行编辑和删除的体验,还是在asp.net这一面的工作流程,都跟gridview是一样的。detailsview和gridview不同的地方是,它还提供了内键的插入支持。

  为了示范detailsview的数据修改功能,首先,添加一个detailsview控件到basics.aspx页面,放在现有的gridview的上方,并通过detailsview的职能标记把它绑定到现有的objectdatasource。然后,清除detailsview的height和width属性,并从它的职能标记中勾选“启用分页”。为了启用编辑、插入和删除支持,只需要简单地从它的职能标记里勾选上“启用插入”、“启用编辑”和“启用删除”。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 17: 配置detailsview支持编辑、插入和删除

与gridview一样,添加编辑、插入或删除支持会添加一个commandfield到该detailsview,如下声明语法所示:

<asp:detailsview id="detailsview1" runat="server" autogeneraterows="false"
  datakeynames="productid" datasourceid="objectdatasource1" allowpaging="true">
  <fields>
    <asp:boundfield datafield="productid"
      headertext="productid" insertvisible="false"
      readonly="true" sortexpression="productid" />
    <asp:boundfield datafield="productname"
      headertext="productname" sortexpression="productname" />
    <asp:boundfield datafield="supplierid" headertext="supplierid"
      sortexpression="supplierid" />
    <asp:boundfield datafield="categoryid" headertext="categoryid"
      sortexpression="categoryid" />
    <asp:boundfield datafield="quantityperunit"
      headertext="quantityperunit"
      sortexpression="quantityperunit" />
    <asp:boundfield datafield="unitprice"
      headertext="unitprice" sortexpression="unitprice" />
    <asp:boundfield datafield="unitsinstock"
      headertext="unitsinstock" sortexpression="unitsinstock" />
    <asp:boundfield datafield="unitsonorder"
      headertext="unitsonorder" sortexpression="unitsonorder" />
    <asp:boundfield datafield="reorderlevel"
      headertext="reorderlevel" sortexpression="reorderlevel" />
    <asp:checkboxfield datafield="discontinued"
      headertext="discontinued" sortexpression="discontinued" />
    <asp:boundfield datafield="categoryname"
      headertext="categoryname" readonly="true"
      sortexpression="categoryname" />
    <asp:boundfield datafield="suppliername"
      headertext="suppliername" readonly="true"
      sortexpression="suppliername" />
    <asp:commandfield showdeletebutton="true"
      showeditbutton="true" showinsertbutton="true" />
  </fields>
</asp:detailsview>

注意detailsview的commandfield默认显示在列集合的下方。因为detailsview的字段是以行的方式呈现的,所以commandfield也表现为包含插入、编辑和删除按钮的一行,出现在detailsview的下方。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 18: 配置detailsview支持编辑、插入和删除

  点击删除按钮就会开始与gridview相同的一系列的事件:一次回传;随之detailsview基于datakeynames的值组成它的objectdatasource的deleteparameters;最后以调用objectdatasource的delete()方法结束,此方法从数据库中删除该产品的记录。在detailsview中编辑也以gridview同样的方式运作。

  为了插入数据,最终用户面对的是一个“新建”按钮,当点击时,detailsview呈现为“插入模式”。在“插入模式”下,新建按钮被“插入”和“取消”按钮取代,并且显示那些insertvisible属性设置为true(默认)的绑定列。这些自增长标识的数据字段,例如productid字段,当通过职能标记绑定该detailsview到数据源的时候让它们的insertvisible属性设置为false 。

  当通过智能标记绑定数据源到detailsview时,visual studio为自增长的字段设置其insertvisible属性为false。只读的字段,像categoryname和suppliername,将显示在“插入模式”下的用户界面中,除非它们的insertvisible属性也明确地设置为false 。稍稍花些时间把这两个字段的insertvisible属性设置为false ,通过detailsview的声明语法或者通过智能标记中的“编辑字段”链接。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 19: northwind商人现在提*品“acme tea”

  在设置好insertvisible属性后,通过浏览器看看这个basics.aspx页面并点击新建按钮。图20显示的是添加一个新的饮料“acme tea”到我们的生产线时的detailsview。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 20: northwind商人现在提*品“acme tea”

  输入acme tea的详细信息并点击插入按钮后,随之发生一次回传并将这个新记录添加到products数据表。因为这个detailsview是按照数据库中的顺序依次列出产品,所以我们必须翻到最后一页才能看到这个新增加的产品。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图21: 产品acme tea的详细信息

注意: detailsview的currentmode 属性指示当前显示的界面并可以被设置为下面几个值之一:edit、insert或readonly。defaultmode属性则指示detailsview在完成一次编辑或插入之后显示的模式,这在需要让detailsview保持编辑或插入模式不变时是很有用的。

  detailsview这个点击插入和编辑的功能跟gridview有相同的局限性:用户必须通过文本框输入存在的categoryid和supplierid值;界面缺少任何验证的逻辑;产品的所有不允许为null值或者没有在数据库中指定默认值的字段必须包含在插入界面里,等等。

  在以后的章节里我们将会研究的扩展和提高gridview的编辑界面的技巧,同样可以应用到detailsview的编辑和插入界面。

使用formview做一个更灵活的数据修改用户界面

  formview控件提供内建的对插入、编辑和删除数据的支持,不过因为它使用模版而不是列,它没有地方让我们添加像gridview和detailsview控件提供给数据修改界面的绑定列和commandfield。取而代之的是,这个界面 – 收集新增一项或编辑现有项时用来收集用户输入的web服务器控件,连同新增、编辑、删除、插入、保存和取消按钮 – 都必须手工添加到适当的模版里。幸运的是,visual studio将在通过它的职能标记的下拉列表绑定formview到数据源时自动地创建需要的界面。

  为了阐明这些技巧,首先,添加一个formview控件到basics.aspx页面,并从formview的职能标记,绑定它到已经存在的objectdatasource。这将为formview生成一个edititemtemplate、insertitemtemplate和itemtemplate ,用textbox服务器控件收集用户的输入并用button服务器控件作为添加新增、编辑、删除、插入、保存和取消按钮。另外,formview的datakeynames属性被设置到objectdatasource所返回的对象的主键(productid)。最后,在formview的职能标记中勾选“起用分页”选项。

  下面展示出formview绑定到objectdatasource后它的itemtemplate声明标记。默认地,每一个除了布尔值以外的产品的字段都绑定到一个label服务器控件的text属性,相应地布尔类型的字段(discontinued)绑定到一个不可更改的checkbox服务器控件的checked属性。为了让新增、编辑和删除按钮点击时能够引发某个formview行为,必要的工作是将它们的commandname属性的值分别设置为new、edit和delete。

<asp:formview id="formview1" runat="server" datakeynames="productid"
  datasourceid="objectdatasource1" allowpaging="true">
  <edititemtemplate>
    ...
  </edititemtemplate>
  <insertitemtemplate>
    ...
  </insertitemtemplate>
  <itemtemplate>
    productid:
    <asp:label id="productidlabel" runat="server"
      text='<%# eval("productid") %>'></asp:label><br />
    productname:
    <asp:label id="productnamelabel" runat="server"
      text='<%# bind("productname") %>'>
    </asp:label><br />
    supplierid:
    <asp:label id="supplieridlabel" runat="server"
      text='<%# bind("supplierid") %>'>
    </asp:label><br />
    categoryid:
    <asp:label id="categoryidlabel" runat="server"
      text='<%# bind("categoryid") %>'>
    </asp:label><br />
    quantityperunit:
    <asp:label id="quantityperunitlabel" runat="server"
      text='<%# bind("quantityperunit") %>'>
    </asp:label><br />
    unitprice:
    <asp:label id="unitpricelabel" runat="server"
      text='<%# bind("unitprice") %>'></asp:label><br />
    unitsinstock:
    <asp:label id="unitsinstocklabel" runat="server"
      text='<%# bind("unitsinstock") %>'>
    </asp:label><br />
    unitsonorder:
    <asp:label id="unitsonorderlabel" runat="server"
      text='<%# bind("unitsonorder") %>'>
    </asp:label><br />
    reorderlevel:
    <asp:label id="reorderlevellabel" runat="server"
      text='<%# bind("reorderlevel") %>'>
    </asp:label><br />
    discontinued:
    <asp:checkbox id="discontinuedcheckbox" runat="server"
      checked='<%# bind("discontinued") %>'
      enabled="false" /><br />
    categoryname:
    <asp:label id="categorynamelabel" runat="server"
      text='<%# bind("categoryname") %>'>
    </asp:label><br />
    suppliername:
    <asp:label id="suppliernamelabel" runat="server"
      text='<%# bind("suppliername") %>'>
    </asp:label><br />
    <asp:linkbutton id="editbutton" runat="server"
      causesvalidation="false" commandname="edit"
      text="edit">
    </asp:linkbutton>
    <asp:linkbutton id="deletebutton" runat="server"
      causesvalidation="false" commandname="delete"
      text="delete">
    </asp:linkbutton>
    <asp:linkbutton id="newbutton" runat="server"
      causesvalidation="false" commandname="new"
      text="new">
    </asp:linkbutton>
  </itemtemplate>
</asp:formview>

图22显示出通过浏览器查看时formview的itemtemplate。列出产品的每一个字段,并且在下方分别由新增、编辑和删除按钮。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 22:  formview默认的itemtemplate列出产品的每一个字段并连同新增、编辑和删除按钮

  类似gridview和detailsview,点击删除按钮 – 或者其它任何一个commandname属性设置为“delete”的button、linkbutton或者imagebutton – 引发一次回传,在formview的datakeynames值的基础上组建objectdatasource的deleteparameters ,并调用objectdatasource的delete()方法。

  当点击编辑按钮时,引发一次回传并且数据重新绑定到edititemtemplate ,它作为开始的编辑界面。这个界面包含为编辑数据用的web服务器控件连同保存和取消按钮。默认的通过visual studio生成的edititemtemplate包含对应自增长字段(productid)的label、对应每一个非布尔型字段的textbox和对应每一个布尔型字段的checkbox 。这个动作与在gridview和detailsview控件里自动生成的绑定列非常相似。

  注意: formview的自动生成的edititemtemplate有一个小问题,就是对于诸如categoryname和suppliername这样的字段将textbox服务器控件呈现为只读。我们马上看看如何解决这个问题。

  在edititemtemplate里的textbox控件的text属性已通过双向绑定的方式绑定到相应的数据字段的值。双向绑定,以<%# bind("datafield") %>表示,在绑定数据到模版和为组装objectdatasource插入或编辑记录的参数时都回执行绑定的动作。就是说,当用户从itemtemplate里点击编辑按钮时,bind()方法返回指定的数据字段的值。用户完成他们的修改并点击报存时,通过bind()指定的数据字段的值回传到objectdatasource的updateparameters 。作为另一种选择,单向绑定,以<%# eval("datafield") %>表示,仅仅在绑定数据到模版时取得数据字段的值,但并不会在回传时将用户输入的值返回到数据源控件的参数。

  下面的声明标记显示了该formview的edititemtemplate。注意这里在绑定语法里用的是bind()方法,并且因此保存和取消按钮设置它们的commandname属性。 

<asp:formview id="formview1" runat="server" datakeynames="productid"
  datasourceid="objectdatasource1" allowpaging="true">
  <edititemtemplate>
    productid:
    <asp:label id="productidlabel1" runat="server"
     text="<%# eval("productid") %>"></asp:label><br />
    productname:
    <asp:textbox id="productnametextbox" runat="server"
     text="<%# bind("productname") %>">
    </asp:textbox><br />
    supplierid:
    <asp:textbox id="supplieridtextbox" runat="server"
     text="<%# bind("supplierid") %>">
    </asp:textbox><br />
    categoryid:
    <asp:textbox id="categoryidtextbox" runat="server"
     text="<%# bind("categoryid") %>">
    </asp:textbox><br />
    quantityperunit:
    <asp:textbox id="quantityperunittextbox" runat="server"
      text="<%# bind("quantityperunit") %>">
    </asp:textbox><br />
    unitprice:
    <asp:textbox id="unitpricetextbox" runat="server"
      text="<%# bind("unitprice") %>">
    </asp:textbox><br />
    unitsinstock:
    <asp:textbox id="unitsinstocktextbox" runat="server"
      text="<%# bind("unitsinstock") %>">
    </asp:textbox><br />
    unitsonorder:
    <asp:textbox id="unitsonordertextbox" runat="server"
      text="<%# bind("unitsonorder") %>">
    </asp:textbox><br />
    reorderlevel:
    <asp:textbox id="reorderleveltextbox" runat="server"
      text="<%# bind("reorderlevel") %>">
    </asp:textbox><br />
    discontinued:
    <asp:checkbox id="discontinuedcheckbox" runat="server"
      checked="<%# bind("discontinued") %>" /><br />
    categoryname:
    <asp:textbox id="categorynametextbox" runat="server"
       text="<%# bind("categoryname") %>">
    </asp:textbox><br />
    suppliername:
    <asp:textbox id="suppliernametextbox" runat="server"
       text="<%# bind("suppliername") %>">
    </asp:textbox><br />
    <asp:linkbutton id="updatebutton" runat="server"
      causesvalidation="true" commandname="update"
      text="update">
    </asp:linkbutton>
    <asp:linkbutton id="updatecancelbutton" runat="server"
      causesvalidation="false" commandname="cancel"
      text="cancel">
    </asp:linkbutton>
  </edititemtemplate>
  <insertitemtemplate>
    ...
  </insertitemtemplate>
  <itemtemplate>
    ...
  </itemtemplate>
</asp:formview>

  在这里我们的edititemtemplate如果我们尝试使用它的话将引起抛出一个异常。问题是categoryname和suppliername字段在edititemtemplate里以textbox服务器控件呈现。我们或者需要把这些textbox替换为label或者干脆把它们删除。让我们就简单地从edititemtemplate里把它们彻底删除吧。

  图23显示的是在产品“chai”上点击编辑按钮后浏览器中的formview。注意显示在itemtemplate里的suppliername和categoryname字段现在不在出现了,因为我们刚刚从edititemtemplate里删除了它们。当点击保存按钮时,formview执行的是与gridview和detailsview控件相似的一系列的步骤。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 23: edititemtemplate默认显示每一个可编辑的产品字段为textbox或checkbox

  当点击formview的itemtemplate中的新建按钮时发生一次回传。不过,没有数据绑定到formview,因为新建了一条记录。该insertitemtemplate界面包含添加新记录用的web服务器控件连同插入和取消按钮。通过visual studio生成的默认的insertitemtemplate包含对应每一个非布尔型字段的textbox和对应布尔型字段的checkbox,类似于自动生成的edititemtemplate的界面。这些textbox控件的text属性通过双向绑定的方式绑定到相应的数据字段。

  下面的声明标记显示了该formview的insertitemtemplate。注意这里的绑定语法使用的是bind()方法并且因此设置了插入和取消按钮的commandname属性。

<asp:formview id="formview1" runat="server" datakeynames="productid"
  datasourceid="objectdatasource1" allowpaging="true">
  <edititemtemplate>
    ...
  </edititemtemplate>
  <insertitemtemplate>
    productname:
    <asp:textbox id="productnametextbox" runat="server"
      text="<%# bind("productname") %>">
    </asp:textbox><br />
    supplierid:
    <asp:textbox id="supplieridtextbox" runat="server"
      text="<%# bind("supplierid") %>">
    </asp:textbox><br />
    categoryid:
    <asp:textbox id="categoryidtextbox" runat="server"
      text="<%# bind("categoryid") %>">
    </asp:textbox><br />
    quantityperunit:
    <asp:textbox id="quantityperunittextbox" runat="server"
      text="<%# bind("quantityperunit") %>">
    </asp:textbox><br />
    unitprice:
    <asp:textbox id="unitpricetextbox" runat="server"
      text="<%# bind("unitprice") %>">
    </asp:textbox><br />
    unitsinstock:
    <asp:textbox id="unitsinstocktextbox" runat="server"
      text="<%# bind("unitsinstock") %>">
    </asp:textbox><br />
    unitsonorder:
    <asp:textbox id="unitsonordertextbox" runat="server"
      text="<%# bind("unitsonorder") %>">
    </asp:textbox><br />
    reorderlevel:
    <asp:textbox id="reorderleveltextbox" runat="server"
      text="<%# bind("reorderlevel") %>">
    </asp:textbox><br />
    discontinued:
    <asp:checkbox id="discontinuedcheckbox" runat="server"
      checked="<%# bind("discontinued") %>" /><br />
    categoryname:
    <asp:textbox id="categorynametextbox" runat="server"
      text="<%# bind("categoryname") %>">
    </asp:textbox><br />
    suppliername:
    <asp:textbox id="suppliernametextbox" runat="server"
      text="<%# bind("suppliername") %>">
    </asp:textbox><br />
    <asp:linkbutton id="insertbutton" runat="server"
      causesvalidation="true" commandname="insert"
      text="insert">
    </asp:linkbutton>
    <asp:linkbutton id="insertcancelbutton" runat="server"
      causesvalidation="false" commandname="cancel"
      text="cancel">
    </asp:linkbutton>
  </insertitemtemplate>
  <itemtemplate>
    ...
  </itemtemplate>
</asp:formview>

  formview的自动生成的insertitemtemplate有一点细微的区别。特别的是,对于只读的字段,例如categoryname和suppliername,也为它们添加了相应的textbox服务器控件。类似edititemtemplate,我们也需要从insertitemtemplate里删除这些textbox。

  图24显示新增一个产品(acme coffee)时浏览器中的formview。注意显示在itemtemplate中的suppliername和categoryname字段现在不再显示了,因为我们刚刚删除了它们。当点击插入按钮时,formview执行的是与gridview和detailsview控件相似的一系列的步骤,插入一条新记录到products表。图25显示了新产品插入成功后在formview中的详细信息。

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 24: insertitemtemplate规定formview的插入界面

在ASP.NET 2.0中操作数据之十六:概述插入、更新和删除数据

图 25: 新增产品acme coffee的详细信息显示在formview中

通过分开read-only、editing和inserting界面到这3个不同的模版,formview可以比detailsview和gridview更高程度地控制这些界面。

注意: 就像detailsview,formview的currentmode属性指示当前显示的界面,而它的defaultmode属性指示编辑或新建完成后formview返回的显示方式。

总结

在这一节里,我们研究了基本的使用gridview、detailsview和formview插入、编辑和删除数据。这三种控件都提供一些内建的数据修改功能,这可以被利用而不需要在asp.net页面里写一行代码,这得益于数据web控件和objectdatasource控件。不过,这个简单的指和点的技巧只能提供出一个简陋的数据修改用户界面。为了提供数据验证、注入编程设置的值、适当地处理异常、自定义用户界面等等,我们就需要依赖于一些在下面几个章节了将讨论的技巧。

祝编程快乐!

作者简介

scott mitchell,著有六本asp/asp.net方面的书,是4guysfromrolla.com的创始人,自1998年以来一直应用微软web技术。scott是个独立的技 术咨询顾问,培训师,作家,最近完成了将由sams出版社出版的新作,24小时内精通asp.net 2.0。他的联系电邮为,也可以通过他的博客http://scottonwriting.net与他联系。

上一篇:

下一篇: