[C#]
private void DemonstrateMergeTable(){
// Create a DataSet with one table, two columns, and ten rows.
DataSet ds = new DataSet("myDataSet");
DataTable t = new DataTable("Items");
// Add table to the DataSet
ds.Tables.Add(t);
// Add columns
DataColumn c1 = new DataColumn("id", Type.GetType("System.Int32"),"");
DataColumn c2 = new DataColumn("Item", Type.GetType("System.Int32"),"");
t.Columns.Add(c1);
t.Columns.Add(c2);
// DataColumn array to set primary key.
DataColumn[] keyCol= new DataColumn[1];
// Set primary key column.
keyCol[0]= c1;
t.PrimaryKey=keyCol;
// Add a RowChanged event handler for the table.
t.RowChanged += new DataRowChangeEventHandler(Row_Changed);
// Add ten rows.
for(int i = 0; i <10;i++){
DataRow r=t.NewRow();
r["id"] = i;
r["Item"]= i;
t.Rows.Add(r);
}
// Accept changes.
ds.AcceptChanges();
PrintValues(ds, "Original values");
// Create a second DataTable identical to the first.
DataTable t2 = t.Clone();
// Add three rows. Note that the id column can't be the
// same as existing rows in the DataSet table.
DataRow newRow;
newRow = t2.NewRow();
newRow["id"] = 14;
newRow["item"] = 774;
//Note the alternative method for adding rows.
t2.Rows.Add(new Object[] { 12, 555 });
t2.Rows.Add(new Object[] { 13, 665 });
// Merge the table into the DataSet
Console.WriteLine("Merging");
ds.Merge(t2);
PrintValues(ds, "Merged With table.");
}
private void Row_Changed(object sender, DataRowChangeEventArgs e){
Console.WriteLine("Row Changed " + e.Action.ToString() + "\t" + e.Row.ItemArray[0]);
}
private void PrintValues(DataSet ds, string label){
Console.WriteLine("\n" + label);
foreach(DataTable t in ds.Tables){
Console.WriteLine("TableName: " + t.TableName);
foreach(DataRow r in t.Rows){
foreach(DataColumn c in t.Columns){
Console.Write("\t " + r[c] );
}
Console.WriteLine();
}
}
}