5.6. Merging Data


You have two DataSet objects with the same schema, but containing different data. You need to combine data from these two DataSet objects without creating duplicate rows.


Use the DataSet.Merge( ) method with the appropriate MissingSchemaAction enumeration values.

The sample code contains four event handlers and a single method:


Sets up the sample by creating two DataSet objects each with a single DataTable containing different subset of data from the Employees table in Northwind. The default view for each table is bound to a data grid on the form.

MergeA Button.Click

The first Button.Click calls the Merge( ) method to merge the first DataSet into the second.

MergeB Button.Click

A second Button.Click calls the Merge( ) method to merge the second DataSet into the first.

Clear Button.Click

A third Button.Click clears the data grid displaying the results of either merge.

Merge( )

This method takes two DataTable arguments. The first DataTable is copied to a new DataTable and the second DataTable is merged into it with the specified MissingSchemaAction. The default view of the result DataTable is bound to a data grid on the form.

The C# code is shown in Example 5-6.

Example 5-6. File: MergingDataForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; private SqlDataAdapter daA, daB; private DataSet dsA, dsB; // . . . private void MergingDataForm_Load(object ...

Get ADO.NET Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.