SqlDataAdapter.RowUpdating 事件
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
Update(DataSet)在对数据源执行命令之前发生。 尝试更新时会触发事件。
public:
event Microsoft::Data::SqlClient::SqlRowUpdatingEventHandler ^ RowUpdating;
public event Microsoft.Data.SqlClient.SqlRowUpdatingEventHandler RowUpdating;
member this.RowUpdating : Microsoft.Data.SqlClient.SqlRowUpdatingEventHandler
Public Custom Event RowUpdating As SqlRowUpdatingEventHandler
事件类型
示例
以下示例演示如何同时使用 RowUpdating 和 RowUpdated 事件。
using System;
using System.Data;
using System.Data.Common;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Data.SqlClient;
public class Form1 : Form
{
private DataSet DataSet1;
private DataGrid dataGrid1;
// handler for RowUpdating event
private static void OnRowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
PrintEventArgs(e);
}
// handler for RowUpdated event
private static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
PrintEventArgs(e);
}
public static int Main()
{
const string connectionString = "Integrated Security=SSPI;database=Northwind;server=MSSQL1";
const string queryString = "SELECT * FROMProducts";
// create DataAdapter
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connectionString);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
// Create and fill DataSet (select only first 5 rows)
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, 0, 5, "Table");
// Modify DataSet
DataTable table = dataSet.Tables["Table"];
table.Rows[0][1] = "new product";
// add handlers
adapter.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating);
adapter.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);
// update, this operation fires two events
// (RowUpdating/RowUpdated) per changed row
adapter.Update(dataSet, "Table");
// remove handlers
adapter.RowUpdating -= new SqlRowUpdatingEventHandler(OnRowUpdating);
adapter.RowUpdated -= new SqlRowUpdatedEventHandler(OnRowUpdated);
return 0;
}
private static void PrintEventArgs(SqlRowUpdatingEventArgs args)
{
Console.WriteLine("OnRowUpdating");
Console.WriteLine(" event args: (" +
" command=" + args.Command +
" commandType=" + args.StatementType +
" status=" + args.Status + ")");
}
private static void PrintEventArgs(SqlRowUpdatedEventArgs args)
{
Console.WriteLine("OnRowUpdated");
Console.WriteLine(" event args: (" +
" command=" + args.Command +
" commandType=" + args.StatementType +
" recordsAffected=" + args.RecordsAffected +
" status=" + args.Status + ")");
}
}
该 RowUpdating 事件返回以下输出:
event args: (command=Microsoft.Data.SqlClient.SqlCommand commandType=2 status=0)
该 RowUpdated 事件返回以下输出:
event args: (command=Microsoft.Data.SqlClient.SqlCommand commandType=2 recordsAffected=1 row=System.Data.DataRow[37] status=0)
注解
使用 Update(DataSet)时,每个数据行更新有两个事件。 执行顺序如下所示:
- DataRow 中的值将移动到参数值。
- 引发 RowUpdating 事件。
- 该命令执行。
- 如果命令设置为
FirstReturnedRecord,则第一个返回的结果将放置在 DataRow中。 - 如果有输出参数,则它们放置在 DataRow中。
- 引发 RowUpdated 事件。
- 调用 AcceptChanges()。