rdquo;),并且键入的数据无误时,才执行插入操作。代码如下 :
protected void Products_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Insert data if the CommandName == "Insert"
// and the validation controls indicate valid data...
if (e.CommandName == "Insert" && Page.IsValid)
{
// TODO: Insert new record...
}
}
注意:
你可能会很奇怪为什么还要检查Page.IsValid属性呢?毕竟,如果在插入界面输 入了无效的数据时,页面回传会中断。检查Page.IsValid属性是为了防止用户未 启用JavaScript或巧妙的绕过客户端验证的情况。简而言之,如果没有进行客户 端进行有效性验证的话,在处理数据以前必须在服务器端再进行一次有效性验证 。
在第1步,ObjectDataSource控件ProductsDataSource的Insert()方法 映射的是ProductsBLL类的AddProduct方法。为了在表Products里添加新记录,我 们只需要简单的调用ObjectDataSource的Insert()方法:
protected void Products_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Insert data if the CommandName == "Insert"
// and the validation controls indicate valid data...
if (e.CommandName == "Insert" && Page.IsValid)
{
// Insert new record
ProductsDataSource.Insert();
}
}
现在可以调用Insert()方法,剩下的步骤是把在插入界面 键入的值传递给ProductsBLL类的AddProduct方法中的参数。就像在教程17章《研 究插入、更新和删除的关联事件》探讨的一样,可以通过ObjectDataSource控件 的Inserting事件来实现。在Inserting事件里,我们需要编程访问页脚行里的控 件,将其值赋给e.InputParameters集合。当用户忽略了某个值时—— 比如使ReorderLevel文本框为空,我们应该指定该值为NULL。因为AddProducts方 法允许那些nullable类型的列接收NULL值。代码如下:
protected void ProductsDataSource_Inserting
(object sender, ObjectDataSourceMethodEventArgs e)
{
// Programmatically reference Web controls in the inserting interface...
TextBox NewProductName =
(TextBox)Products.FooterRow.FindControl ("NewProductName");
DropDownList NewCategoryID =
(DropDownList)Products.FooterRow.FindControl ("NewCategoryID");
DropDownList NewSupplierID =
(DropDownList)Products.FooterRow.FindControl ("NewSupplierID");
TextBox NewQuantityPerUnit =
(TextBox)Products.FooterRow.FindControl ("NewQuantityPerUnit");
TextBox NewUnitPrice =
(TextBox)Products.FooterRow.FindControl ("NewUnitPrice");
TextBox NewUnitsInStock =
(TextBox)Products.FooterRow.FindControl ("NewUnitsInStock");
TextBox NewUnitsOnOrder =
(TextBox)Products.FooterRow.FindControl ("NewUnitsOnOrder");
TextBox NewReorderLevel =
(TextBox)Products.FooterRow.FindControl ("NewReorderLevel");
CheckBox NewDiscontinued =
(CheckBox)Products.FooterRow.FindControl ("NewDiscontinued");
// Set the ObjectDataSource''s InsertParameters values...
e.InputParameters["productName"] = NewProductName.Text;
e.InputParameters["s
|