5.6. Merging Data
Problem
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.
Solution
Use the DataSet.Merge( )
method with the appropriate
MissingSchemaAction
enumeration values.
The sample code contains four event handlers and a single method:
Form.Load
Sets up the sample by creating two
DataSet
objects each with a singleDataTable
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 theMerge( )
method to merge the firstDataSet
into the second.- MergeB
Button.Click
A second
Button.Click
calls theMerge( )
method to merge the secondDataSet
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 firstDataTable
is copied to a newDataTable
and the secondDataTable
is merged into it with the specifiedMissingSchemaAction
. The default view of the resultDataTable
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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.