SqlDataSourceCommandEventArgs 类在 SqlDataSource控件中的应用

Calchas 发表于 2009, August 20, 8:40 AM

MSDN说明:
因为 SqlDataSourceCommandEventArgs 类是从 CancelEventArgs 类派生的,所以可以通过将

Cancel 属性设置为 true,取消挂起的 SqlDataSource 数据库命令。通过访问由 Command 属

性公开的 DbCommand 对象,可以在运行此命令之前,检查和操作 CommandText、Parameters

集合以及其他命令属性。

OnUpdating、OnInserting 和 OnDeleting 方法使用 SqlDataSourceCommandEventArgs 类,以

在运行 SqlDataSource 数据库命令前提供对此命令的访问。SqlDataSource 控件公开了许多事

件,可处理这些事件以在数据操作过程中使用基础数据对象。下表列出了这些事件、关联的

EventArgs 和事件处理程序类,以更好地引导您使用各种与使用 SqlDataSource 控件的数据操

作的生存期相对应的事件。
示例一:
MSDN的updating/updated事件片段
该示例演示,当使用 SqlDataSource 控件更新数据时,如何使用 DbTransaction 对象来添加

事务上下文。
private void OnSqlUpdating(Object source, SqlDataSourceCommandEventArgs e) {
DbCommand command = e.Command;
DbConnection cx = command.Connection;
cx.Open();
DbTransaction tx = cx.BeginTransaction();
command.Transaction = tx;
}

private void OnSqlUpdated(Object source, SqlDataSourceStatusEventArgs e) {
DbCommand command = e.Command;
DbTransaction tx = command.Transaction;

// In this code example the OtherProcessSucceeded variable represents
// the outcome of some other process that occurs whenever the data is
// updated, and must succeed for the data change to be committed. For
// simplicity, we set this value to true.
bool OtherProcessSucceeded = true;

if (OtherProcessSucceeded) {
tx.Commit();
Label2.Text=”The record was updated successfully!”;
}
else {
tx.Rollback();
Label2.Text=”The record was not updated.”;
}
}
示例二:数据插入过程中更改数据
//根据 @slevel传递来的数据,改变@fk参数中的数据
protected void SqlDataSource_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
//@slevel为Sql语句中参数
if (e.Command.Parameters["@slevel"].Value == “C级”)
e.Command.Parameters["@FK"].Value = 30;
}
示例三:取消删除
protected void SqlDataSource_Deleting(object sender, SqlDataSourceCommandEventArgs e)
{
if (e.Command.Parameters["@输入日期"].Value == null)
e.Cancel = true;
}

« 上一篇 | 下一篇 »

引用: 点击获得Trackback地址,Encode: UTF-8 点击获得Trackback地址,Encode: GB2312 or GBK 点击获得Trackback地址,Encode: BIG5
发表评论:( 你的参与是我最大的动力! )