Your updates are not getting written back to the main database because when you do the .Merge
the new rows are added to the DataTable with their current .RowStatus
in the other DataTable, which is Unchanged
. So, when you call the .Update
method the main DataTable has more rows than it did before, but they are all flagged as Unchanged
so the OleDbDataAdapter assumes that it has nothing to do.
Instead, you need to .Add
the new DataRows to the main DataTable so their status will be Added
when the .Update
takes place. The following code works for me. (It's C# code, but it shouldn't be too difficult to map it back to VB.NET.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace mergeTest
{
class Program
{
static void Main(string[] args)
{
using (OleDbConnection conExisting = new OleDbConnection())
{
conExisting.ConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=C:\__tmp\data\existingStuff.mdb;";
conExisting.Open();
using (OleDbDataAdapter daExisting = new OleDbDataAdapter())
{
daExisting.SelectCommand = new OleDbCommand();
daExisting.SelectCommand.Connection = conExisting;
daExisting.SelectCommand.CommandText = "SELECT * FROM Items";
var dtExisting = new System.Data.DataTable();
daExisting.Fill(dtExisting);
Console.WriteLine(string.Format("dtExisting has {0} rows", dtExisting.Rows.Count));
using (OleDbConnection conNew = new OleDbConnection())
{
conNew.ConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=C:\__tmp\data\newStuff.mdb;";
conNew.Open();
using (OleDbDataAdapter daNew = new OleDbDataAdapter())
{
daNew.SelectCommand = new OleDbCommand();
daNew.SelectCommand.Connection = conNew;
daNew.SelectCommand.CommandText = "SELECT * FROM Items";
var dtNew = new System.Data.DataTable();
daNew.Fill(dtNew);
foreach (System.Data.DataRow drNew in dtNew.Rows)
{
System.Data.DataRow drExisting = dtExisting.NewRow();
drExisting.ItemArray = drNew.ItemArray; // copy columns
dtExisting.Rows.Add(drExisting);
}
Console.WriteLine(string.Format("dtExisting now has {0} rows:", dtExisting.Rows.Count));
foreach (System.Data.DataRow dr in dtExisting.Rows)
{
Console.WriteLine(String.Format("ID={0}, RowState={1}", dr["ID"], dr.RowState));
}
}
conNew.Close();
}
OleDbCommandBuilder cbExisting = new OleDbCommandBuilder(daExisting);
cbExisting.QuotePrefix = "[";
cbExisting.QuoteSuffix = "]";
daExisting.Update(dtExisting);
}
conExisting.Close();
}
Console.WriteLine();
Console.WriteLine("Done.");
Console.ReadKey();
}
}
}
Using my test data, the console output is:
dtExisting has 3 rows
dtExisting now has 6 rows:
ID=existing1, RowState=Unchanged
ID=existing2, RowState=Unchanged
ID=existing3, RowState=Unchanged
ID=new1, RowState=Added
ID=new2, RowState=Added
ID=new3, RowState=Added
Done.