using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace UseDataAdapter
{
/// <summary>
/// Update 的摘要说明。
/// </summary>
public class UpdateEvent : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid dgShow;
protected System.Web.UI.WebControls.Button btnUpdate;
private void Page_Load(object sender, System.EventArgs e)
{
// Create the DataSet and DataAdapter
SqlConnection myConnection = new SqlConnection( "server=(local);uid=sa;pwd=111;database=Pubs" );
DataSet myDataSet = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter("Select * From Authors", myConnection );
myDataAdapter.Fill( myDataSet, "Authors" );
dgShow.DataSource = myDataSet.Tables[0].DefaultView;
dgShow.DataBind();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnUpdate_Click(object sender, System.EventArgs e)
{
// Create the DataSet and DataAdapter
SqlConnection myConnection = new SqlConnection( "server=(local);uid=sa;pwd=111;database=Pubs" );
DataSet myDataSet = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter("Select * From Authors", myConnection );
//
myDataAdapter.RowUpdating += new SqlRowUpdatingEventHandler(MyUpdatingHandler);
myDataAdapter.RowUpdated += new SqlRowUpdatedEventHandler(MyUpdatedHandler);
myDataAdapter.Fill( myDataSet, "Authors" );
// Change value of first row
myDataSet.Tables[ "Authors" ].Rows[ 0 ][ "au_fname" ] = "Johns";
// Update the Database Table
SqlCommandBuilder myBuilder = new SqlCommandBuilder( myDataAdapter );
myDataAdapter.Update( myDataSet, "Authors" );
dgShow.DataSource = myDataSet.Tables[0].DefaultView;
dgShow.DataBind();
}
public void MyUpdatingHandler(object adapter,SqlRowUpdatingEventArgs e)
{
switch(e.StatementType)
{
case StatementType.Update:
{
SqlConnection myConnection = new SqlConnection( "server=(local);uid=sa;pwd=111;database=Pubs" );
string strSql = "Select * From Authors where au_fname='"
+e.Row["au_fname",DataRowVersion.Original]+"'";
SqlCommand com = new SqlCommand(strSql,myConnection);
myConnection.Open();
if(com.ExecuteNonQuery()==0)
{
Response.Write("出错!有用户已经修改过数据集!");
e.Status = UpdateStatus.ErrorsOccurred;//报错
}
myConnection.Close();
break;
}
}
}
public void MyUpdatedHandler(object adapter,SqlRowUpdatedEventArgs e)
{
switch(e.StatementType)
{
case StatementType.Update:
if(e.Status==UpdateStatus.ErrorsOccurred)
e.Status = UpdateStatus.SkipCurrentRow;
break;
}
}
}
}