KnowDotNet

A cool new feature of the DataAdapter in ADO.NET 2.0

by William Ryan

Just came across something that was totally by accident - the SqlDataAdapter's .AcceptChangesDuringUpdate method.  Back in the day, as in now, when you call the Update method, the AcceptChanges method of the DataSet / DataRow class(es) is called as each row is updated.  This can be a pain if you want to simulate transactional behavior.   Personally I haven't found it to be inconvenient, but I've seen many posts where people have.  Anyway, that's no longer an issue thanks to the ADO.NET team:

//Declare a few variables...

private SqlConnection cn;

private SqlDataAdapter da;

private SqlCommand cmd;

private DataSet ds;

private SqlCommandBuilder cb = new SqlCommandBuilder();


//Instantiate everything we need

private void Form1_Load(object sender, EventArgs e)

{

       cn = new SqlConnection("integrated security=SSPI;data source=xxxxx;initial   catalog=xxxx");

       cmd = new SqlCommand("SELECT TOP 100 * FROM Source", cn);

       da = new SqlDataAdapter(cmd);

       cb.DataAdapter = da;

}

//Load the DataSet/DataTable and Bind it to a DataGridView control

private void btnLoad1_Click(object sender, EventArgs e)

{

    ds = new DataSet();

      try

      {

         da.Fill(ds, "MyTable");

      }

      catch (SqlException ex)

      {

         System.Diagnostics.Debug.Assert(false, ex.ToString());

      }

      finally { cn.Close(); }

      dgv.DataSource = ds.Tables[0];

}

private void btnLoadDb_Click(object sender, EventArgs e)

{

     //Set this to False so acceptchanges isn't called

     da.AcceptChangesDuringUpdate = false;

     System.Diagnostics.Debug.Assert(ds.HasChanges);//Passes

     try

     {

         da.Update(ds.Tables[0]);

     }

     catch (SqlException ex)

     {

        System.Diagnostics.Debug.Assert(false, ex.ToString());

     }

     finally { cn.Close();}

     System.Diagnostics.Debug.Assert(ds.HasChanges);//Passes

     //Proving that Changes weren't called.

}