在ASP.NET 2.0中操作数据之二十八:GridView里的But(3)

  象在以前的教程里所做的那样,我们使用自底向上的方法,首先创建DAL 的方法,然后是BLL ,最后在 ASP.NET page里实现这个功能.打开App_Code/DAL文件夹里的Northwind.xsd ,为ProductsTableAdapter 添加一个新方法(右键点击ProductsTableAdapter ,选择Add Query).这样弹出TableAdapter Query 的配置向导.首先指定DAL 需要使用的SQL .

/uploads/allimg/200612/1K41Vb0_0.png

图 12: 使用SQL Statement创建DAL 方法

  接着,向导会询问我们创建哪种类型的query .由于DiscontinueAllProductsForSupplier(supplierID)需要更新Products表,为指定的supplierID 的所有products的Discontinued 字段设置为1,因此我们需要创建一个更新数据的query .

/uploads/allimg/200612/1K4253b8_0.png

图 13: 选择UPDATE Query的类型

  下一个向导显示的窗口提供了TableAdapter的已经存在的UPDATE 语句,它会updates 在Products DataTable定义的所有的字段.用下面的语句替换它:

UPDATE [Products] SET
   Discontinued = 1
WHERE SupplierID = @SupplierID

  输入以上语句后点Next,最后一个向导窗口需要输入该方法的名字—DiscontinueAllProductsForSupplier.完成向导后点Finish  button.当你回到DataSet 设计器时你应该可以在ProductsTableAdapter 看到名为DiscontinueAllProductsForSupplier(@SupplierID)的方法.

/uploads/allimg/200612/1K4195594_0.png

图 14: 为 DAL 的方法取名为 DiscontinueAllProductsForSupplier

/uploads/allimg/200612/1K41c033_0.png

  完成Data Access Layer里的DiscontinueAllProductsForSupplier(supplierID)方法后,我们下一步的任务是创建Business Logic Layer里的相应的方法.打开ProductsBLL 类文件,添加以下内容:

public int DiscontinueAllProductsForSupplier(int supplierID) { return Adapter.DiscontinueAllProductsForSupplier(supplierID); }

  这个方法仅仅是调用DAL里的DiscontinueAllProductsForSupplier(supplierID)方法,并传递提供的supplierID  参数.如果有一些业务规则规定仅仅允许在一定的条件下supplier的products 才能被停止使用,那么这些规则应该写在这里(BLL).

  注意:和ProductsBLL 类的UpdateProduct重载不一样,DiscontinueAllProductsForSupplier(supplierID)的签名不包括DataObjectMethodAttribute 属性(<System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, Boolean)>).这个将DiscontinueAllProductsForSupplier(supplierID) 方法从ObjectDataSource的配置数据源向导的UPDATE标签里的下拉列表中排除.我之所以忽略这个属性是因为我们会在ASP.NET page里直接通过event handler 调用DiscontinueAllProductsForSupplier(supplierID)方法.

第五步: 为FormView添加一个“Discontinue All Products” Button

  完成了BLL 和 DAL 里的DiscontinueAllProductsForSupplier(supplierID)方法后,我们来做实现停止使用选定的supplier的所有product的功能最后一步:为 FormView的 ItemTemplate添加Button .我们将这个Button 添加在supplier的phone number下,Text为“Discontinue All Products”,ID为DiscontinueAllProductsForSupplier.你可以通过FormView的智能标签里的Edit Templates 来添加这个Button (见图15),或直接修改代码.

/uploads/allimg/200612/1K41c033_0.png

图 15: 为FormView的ItemTemplate添加 “Discontinue All Products” Button

  当用户点击这个Button 时,页面会回发,FormView的ItemCommand event被激发.我们可以为这个事件创建一个event handler ,用来在Button 被点击时执行自定义代码.注意,任何时候FormView里的任何Button, LinkButton, 或 ImageButton被点击时,ItemCommand 事件都会被激发.这意味着当用户在FormView里从一个页面跳到另一个页面时,ItemCommand 事件会被激发.当用户点击一个支持inserting, updating, 或 deleting的FormView里的New, Edit, 或 Delete 时,ItemCommand 事件会被激发.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjwwff.html