DataSet.Merge Method

Definition

Merges a specified DataSet, DataTable, or array of DataRow objects into the current DataSet or DataTable.

Overloads

Merge(DataRow[])

Merges an array of DataRow objects into the current DataSet.

Merge(DataSet)

Merges a specified DataSet and its schema into the current DataSet.

Merge(DataTable)

Merges a specified DataTable and its schema into the current DataSet.

Merge(DataSet, Boolean)

Merges a specified DataSet and its schema into the current DataSet, preserving or discarding any changes in this DataSet according to the given argument.

Merge(DataRow[], Boolean, MissingSchemaAction)

Merges an array of DataRow objects into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

Merge(DataSet, Boolean, MissingSchemaAction)

Merges a specified DataSet and its schema with the current DataSet, preserving or discarding changes in the current DataSet and handling an incompatible schema according to the given arguments.

Merge(DataTable, Boolean, MissingSchemaAction)

Merges a specified DataTable and its schema into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

Merge(DataRow[])

Source:
DataSet.cs
Source:
DataSet.cs
Source:
DataSet.cs

Merges an array of DataRow objects into the current DataSet.

C#
public void Merge(System.Data.DataRow[] rows);

Parameters

rows
DataRow[]

The array of DataRow objects to be merged into the DataSet.

Remarks

The Merge method is used to merge two DataSet objects that have largely similar schemas. A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. This allows the client application to have a refreshed DataSet with the latest data from the data source.

The Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. In this scenario, the GetChanges method is first invoked. That method returns a second DataSet optimized for validating and merging. This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. This subset is generally smaller and thus more efficiently passed back to a middle-tier component. The middle-tier component then updates the original data source with the changes through stored procedures. The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. In that case, the merged DataSet contains the added schema and data.

After merging schemas, the data is merged.

When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

During a merge, constraints are disabled. If any constraints cannot be enabled at the end of a merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. The errors must be resolved before attempting to reset the EnforceConstraints property to true.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Merge(DataSet)

Source:
DataSet.cs
Source:
DataSet.cs
Source:
DataSet.cs

Merges a specified DataSet and its schema into the current DataSet.

C#
public void Merge(System.Data.DataSet dataSet);

Parameters

dataSet
DataSet

The DataSet whose data and schema will be merged.

Exceptions

One or more constraints cannot be enabled.

The dataSet is null.

Examples

The following example uses the GetChanges, Update, and Merge methods on a DataSet.

C#
private void DemonstrateMerge()
{
    // Create a DataSet with one table, two columns, and three rows.
    DataSet dataSet = new DataSet("dataSet");
    DataTable table = new DataTable("Items");
    DataColumn idColumn = new DataColumn("id",
        Type.GetType("System.Int32"));
    idColumn.AutoIncrement=true;
    DataColumn itemColumn = new DataColumn("Item",
        Type.GetType("System.Int32"));

    // DataColumn array to set primary key.
    DataColumn[] keyColumn= new DataColumn[1];
    DataRow row;

    // Create variable for temporary DataSet.
    DataSet changeDataSet;

    // Add columns to table, and table to DataSet.
    table.Columns.Add(idColumn);
    table.Columns.Add(itemColumn);
    dataSet.Tables.Add(table);

    // Set primary key column.
    keyColumn[0]= idColumn;
    table.PrimaryKey=keyColumn;

    // Add ten rows.
    for(int i = 0; i <10;i++)
    {
        row=table.NewRow();
        row["Item"]= i;
        table.Rows.Add(row);
    }

    // Accept changes.
    dataSet.AcceptChanges();
    PrintValues(dataSet, "Original values");

    // Change two row values.
    table.Rows[0]["Item"]= 50;
    table.Rows[1]["Item"]= 111;

    // Add one row.
    row=table.NewRow();
    row["Item"]=74;
    table.Rows.Add(row);

    // Insert code for error checking. Set one row in error.
    table.Rows[1].RowError= "over 100";
    PrintValues(dataSet, "Modified and New Values");
    // If the table has changes or errors, create a subset DataSet.
    if(dataSet.HasChanges(DataRowState.Modified |
        DataRowState.Added)& dataSet.HasErrors)
    {
        // Use GetChanges to extract subset.
        changeDataSet = dataSet.GetChanges(
            DataRowState.Modified|DataRowState.Added);
        PrintValues(changeDataSet, "Subset values");
        // Insert code to reconcile errors. In this case reject changes.
        foreach(DataTable changeTable in changeDataSet.Tables)
        {
            if (changeTable.HasErrors)
            {
                foreach(DataRow changeRow in changeTable.Rows)
                {
                    //Console.WriteLine(changeRow["Item"]);
                    if((int)changeRow["Item",
                        DataRowVersion.Current ]> 100)
                    {
                        changeRow.RejectChanges();
                        changeRow.ClearErrors();
                    }
                }
            }
        }
        PrintValues(changeDataSet, "Reconciled subset values");
        // Merge changes back to first DataSet.
        dataSet.Merge(changeDataSet);
        PrintValues(dataSet, "Merged Values");
    }
}

private void PrintValues(DataSet dataSet, string label)
{
    Console.WriteLine("\n" + label);
    foreach(DataTable table in dataSet.Tables)
    {
        Console.WriteLine("TableName: " + table.TableName);
        foreach(DataRow row in table.Rows)
        {
            foreach(DataColumn column in table.Columns)
            {
                Console.Write("\table " + row[column] );
            }
            Console.WriteLine();
        }
    }
}

Remarks

The Merge method is used to merge two DataSet objects that have largely similar schemas. A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. This allows the client application to have a refreshed DataSet with the latest data from the data source.

The Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. In this scenario, the GetChanges method is first invoked. That method returns a second DataSet optimized for validating and merging. This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. The middle-tier component then updates the original data source with the changes through stored procedures. The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. In that case, the merged DataSet contains the added schema and data.

After merging schemas, the data is merged.

When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

During a merge, constraints are disabled. If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. The errors must be resolved before attempting to reset the EnforceConstraints property to true.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Merge(DataTable)

Source:
DataSet.cs
Source:
DataSet.cs
Source:
DataSet.cs

Merges a specified DataTable and its schema into the current DataSet.

C#
public void Merge(System.Data.DataTable table);

Parameters

table
DataTable

The DataTable whose data and schema will be merged.

Exceptions

The table is null.

Examples

The following example creates a simple DataSet with one table, two columns, and ten rows. A second DataTable is created that is identical to the first. Two rows are added to the second table, which is then merged into the DataSet.

C#
private void DemonstrateMergeTable()
{
    // Create a DataSet with one table, two columns, and ten rows.
    DataSet dataSet = new DataSet("dataSet");
    DataTable table = new DataTable("Items");

    // Add table to the DataSet
    dataSet.Tables.Add(table);

    // Add columns
    DataColumn c1 = new DataColumn("id",
        Type.GetType("System.Int32"),"");
    DataColumn c2 = new DataColumn("Item",
        Type.GetType("System.Int32"),"");
    table.Columns.Add(c1);
    table.Columns.Add(c2);

    // DataColumn array to set primary key.
    DataColumn[] keyCol= new DataColumn[1];

    // Set primary key column.
    keyCol[0]= c1;
    table.PrimaryKey=keyCol;

    // Add a RowChanged event handler for the table.
    table.RowChanged += new
        DataRowChangeEventHandler(Row_Changed);

    // Add ten rows.
    for(int i = 0; i <10;i++)
    {
        DataRow row=table.NewRow();
        row["id"] = i;
        row["Item"]= i;
        table.Rows.Add(row);
    }
    // Accept changes.
    dataSet.AcceptChanges();

    PrintValues(dataSet, "Original values");

    // Create a second DataTable identical to the first.
    DataTable t2 = table.Clone();

    // Add three rows. Note that the id column can'te 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");
    dataSet.Merge(t2);
    PrintValues(dataSet, "Merged With table.");
}

private void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row Changed " + e.Action.ToString()
        + "\table" + e.Row.ItemArray[0]);
}

private void PrintValues(DataSet dataSet, string label)
{
    Console.WriteLine("\n" + label);
    foreach(DataTable table in dataSet.Tables)
    {
        Console.WriteLine("TableName: " + table.TableName);
        foreach(DataRow row in table.Rows)
        {
            foreach(DataColumn column in table.Columns)
            {
                Console.Write("\table " + row[column] );
            }
            Console.WriteLine();
        }
    }
}

Remarks

The Merge method is used to merge two DataSet objects that have largely similar schemas. A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. This allows the client application to have a refreshed DataSet with the latest data from the data source.

The Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. In this scenario, the GetChanges method is first invoked. That method returns a second DataSet optimized for validating and merging. This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. The middle-tier component then updates the original data source with the changes through stored procedures. The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. In that case, the merged DataSet contains the added schema and data.

After merging schemas, the data is merged.

When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

During a merge, constraints are disabled. If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. The errors must be resolved before attempting to reset the EnforceConstraints property to true.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Merge(DataSet, Boolean)

Source:
DataSet.cs
Source:
DataSet.cs
Source:
DataSet.cs

Merges a specified DataSet and its schema into the current DataSet, preserving or discarding any changes in this DataSet according to the given argument.

C#
public void Merge(System.Data.DataSet dataSet, bool preserveChanges);

Parameters

dataSet
DataSet

The DataSet whose data and schema will be merged.

preserveChanges
Boolean

true to preserve changes in the current DataSet; otherwise, false.

Examples

The following example creates a simple DataSet with one table, two columns, and ten rows. After adding ten rows, two values are changed, and one row is added. A subset of the changed data is created using the GetChanges method. After reconciling errors, the subset data is merged into the original DataSet.

C#
private void DemonstrateMerge()
{
    // Create a DataSet with one table, two columns,
    // and three rows.
    DataSet dataSet = new DataSet("dataSet");
    DataTable table = new DataTable("Items");
    DataColumn idColumn = new DataColumn("id",
        Type.GetType("System.Int32"),"");
    idColumn.AutoIncrement=true;
    DataColumn itemColumn = new DataColumn("Item",
        Type.GetType("System.Int32"),"");

    // DataColumn array to set primary key.
    DataColumn[] keyColumn= new DataColumn[1];
    DataRow row;

    // Create variable for temporary DataSet.
    DataSet changesDataSet;

    // Add RowChanged event handler for the table.
    table.RowChanged+=new DataRowChangeEventHandler(
        Row_Changed);
    dataSet.Tables.Add(table);
    table.Columns.Add(idColumn);
    table.Columns.Add(itemColumn);

    // Set primary key column.
    keyColumn[0]= idColumn;
    table.PrimaryKey=keyColumn;
    // Add ten rows.
    for(int i = 0; i <10;i++)
    {
        row=table.NewRow();
        row["Item"]= i;
        table.Rows.Add(row);
    }
    // Accept changes.
    dataSet.AcceptChanges();
    PrintValues(dataSet, "Original values");

    // Change row values.
    table.Rows[0]["Item"]= 50;
    table.Rows[1]["Item"]= 111;

    // Add one row.
    row=table.NewRow();
    row["Item"]=74;
    table.Rows.Add(row);

    // Insert code for error checking. Set one row in error.
    table.Rows[1].RowError= "over 100";
    PrintValues(dataSet, "Modified and New Values");

    // If the table has changes or errors,
    // create a subset DataSet.
    if(dataSet.HasChanges(DataRowState.Modified |
        DataRowState.Added)&& dataSet.HasErrors)
    {
        // Use GetChanges to extract subset.
        changesDataSet = dataSet.GetChanges(
            DataRowState.Modified|DataRowState.Added);
        PrintValues(changesDataSet, "Subset values");

        // Insert code to reconcile errors. In this case, reject changes.
        foreach(DataTable changesTable in changesDataSet.Tables)
        {
            if (changesTable.HasErrors)
            {
                foreach(DataRow changesRow in changesTable.Rows)
                {
                    //Console.WriteLine(changesRow["Item"]);
                    if((int)changesRow["Item",DataRowVersion.Current ]> 100)
                    {
                        changesRow.RejectChanges();
                        changesRow.ClearErrors();
                    }
                }
            }
        }
        // Add a column to the changesDataSet.
        changesDataSet.Tables["Items"].Columns.Add(
            new DataColumn("newColumn"));
        PrintValues(changesDataSet, "Reconciled subset values");
        // Merge changes back to first DataSet.
        dataSet.Merge(changesDataSet, false,
            System.Data.MissingSchemaAction.Add);
    }
    PrintValues(dataSet, "Merged Values");
}

private void Row_Changed(object sender, DataRowChangeEventArgs e)
{
    Console.WriteLine("Row Changed " + e.Action.ToString()
        + "\table" + e.Row.ItemArray[0]);
}

private void PrintValues(DataSet dataSet, string label)
{
    Console.WriteLine(label + "\n");
    foreach(DataTable table in dataSet.Tables)
    {
        Console.WriteLine("TableName: " + table.TableName);
        foreach(DataRow row in table.Rows)
        {
            foreach(DataColumn column in table.Columns)
            {
                Console.Write("\table " + row[column] );
            }
            Console.WriteLine();
        }
    }
}

Remarks

The Merge method is used to merge two DataSet objects that have largely similar schemas. A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. This allows the client application to have a refreshed DataSet with the latest data from the data source.

The Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. In this scenario, the GetChanges method is first invoked. That method returns a second DataSet optimized for validating and merging. This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. The middle-tier component then updates the original data source with the changes through stored procedures. The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. In that case, the merged DataSet contains the added schema and data.

After merging schemas, the data is merged.

When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

During a merge, constraints are disabled. If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. The errors must be resolved before attempting to reset the EnforceConstraints property to true.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Merge(DataRow[], Boolean, MissingSchemaAction)

Source:
DataSet.cs
Source:
DataSet.cs
Source:
DataSet.cs

Merges an array of DataRow objects into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

C#
public void Merge(System.Data.DataRow[] rows, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction);

Parameters

rows
DataRow[]

The array of DataRow objects to be merged into the DataSet.

preserveChanges
Boolean

true to preserve changes in the DataSet; otherwise, false.

missingSchemaAction
MissingSchemaAction

One of the MissingSchemaAction values.

Remarks

The Merge method is used to merge two DataSet objects that have largely similar schemas. A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. This allows the client application to have a refreshed DataSet with the latest data from the data source.

The Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. In this scenario, the GetChanges method is first invoked. That method returns a second DataSet optimized for validating and merging. This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. The middle-tier component then updates the original data source with the changes through stored procedures. The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

To facilitate explanation of the Merge method, we use "target" to signify the current DataSet, and "source" to name the second (parameter) DataSet. The target DataSet is so named because it is the object upon which an action (the merge) occurs. The second DataSet is called a "source" because the information it contains does not change, but instead is merged into the current DataSet.

When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. In that case, the merged DataSet contains the added schema and data.

After merging schemas, the data is merged.

When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

During a merge, constraints are disabled. If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. The errors must be resolved before attempting to reset the EnforceConstraints property to true.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Merge(DataSet, Boolean, MissingSchemaAction)

Source:
DataSet.cs
Source:
DataSet.cs
Source:
DataSet.cs

Merges a specified DataSet and its schema with the current DataSet, preserving or discarding changes in the current DataSet and handling an incompatible schema according to the given arguments.

C#
public void Merge(System.Data.DataSet dataSet, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction);

Parameters

dataSet
DataSet

The DataSet whose data and schema will be merged.

preserveChanges
Boolean

true to preserve changes in the current DataSet; otherwise, false.

missingSchemaAction
MissingSchemaAction

One of the MissingSchemaAction values.

Exceptions

The dataSet is null.

Examples

The following example creates a simple DataSet with one table, two columns, and ten rows. Two values are changed, and one row is added. A subset of the changed data is created using the GetChanges method. After reconciling errors, a new column is added to the subset, changing the schema. When the Merge method is called with the missingSchemaAction set to MissingSchemaAction.Add, the new column is added to the original DataSet object's schema.

C#
private void DemonstrateMergeMissingSchema()
{
    // Create a DataSet with one table, two columns,
    // and three rows.
    DataSet dataSet = new DataSet("dataSet");
    DataTable table = new DataTable("Items");
    DataColumn idColumn = new DataColumn("id",
        Type.GetType("System.Int32"));
    idColumn.AutoIncrement=true;
    DataColumn itemColumn = new DataColumn("Item",
        Type.GetType("System.Int32"));
    // DataColumn array to set primary key.

    DataColumn[] keyColumn= new DataColumn[1];
    DataRow row;
    // Create variable for temporary DataSet.
    DataSet changeDataSet;

    // Add RowChanged event handler for the table.
    table.RowChanged+= new DataRowChangeEventHandler(
        Row_Changed);
    dataSet.Tables.Add(table);
    table.Columns.Add(idColumn);
    table.Columns.Add(itemColumn);

    // Set primary key column.
    keyColumn[0]= idColumn;
    table.PrimaryKey=keyColumn;

    // Add ten rows.
    for(int i = 0; i <10;i++)
    {
        row=table.NewRow();
        row["Item"]= i;
        table.Rows.Add(row);
    }

    // Accept changes.
    dataSet.AcceptChanges();
    PrintValues(dataSet, "Original values");

    // Change row values.
    table.Rows[0]["Item"]= 50;
    table.Rows[1]["Item"]= 111;

    // Add one row.
    row=table.NewRow();
    row["Item"]=74;
    table.Rows.Add(row);

    // Insert code for error checking. Set one row in error.
    table.Rows[1].RowError= "over 100";
    PrintValues(dataSet, "Modified and New Values");
    // If the table has changes or errors, create a subset DataSet.
    if(dataSet.HasChanges(DataRowState.Modified |
        DataRowState.Added)& dataSet.HasErrors)
    {
        // Use GetChanges to extract subset.
        changeDataSet = dataSet.GetChanges(
            DataRowState.Modified|DataRowState.Added);
        PrintValues(changeDataSet, "Subset values");

        // Insert code to reconcile errors. Reject the changes.
        foreach(DataTable changeTable in changeDataSet.Tables)
        {
            if (changeTable.HasErrors)
            {
                foreach(DataRow changeRow in changeTable.Rows)
                {
                    //Console.WriteLine(changeRow["Item"]);
                    if((int)changeRow["Item",
                        DataRowVersion.Current ]> 100)
                    {
                        changeRow.RejectChanges();
                        changeRow.ClearErrors();
                    }
                }
            }
        }
        // Add a column to the changeDataSet to change the schema.
        changeDataSet.Tables["Items"].Columns.Add(
            new DataColumn("newColumn"));
        PrintValues(changeDataSet, "Reconciled subset values");

        // Add values to the rows for each column.
        foreach(DataRow rowItem in changeDataSet.Tables["Items"].Rows)
        {
            rowItem["newColumn"] = "my new schema value";
        }
        // Merge changes back to first DataSet.
        dataSet.Merge(changeDataSet, false,
            System.Data.MissingSchemaAction.Add);
    }
    PrintValues(dataSet, "Merged Values");
}

private void Row_Changed(object sender, DataRowChangeEventArgs e)
{
    Console.WriteLine("Row Changed " + e.Action.ToString()
        + "\table" + e.Row.ItemArray[0]);
}

private void PrintValues(DataSet dataSet, string label)
{
    Console.WriteLine("\n" + label);
    foreach(DataTable table in dataSet.Tables)
    {
        Console.WriteLine("TableName: " + table.TableName);
        foreach(DataRow row in table.Rows)
        {
            foreach(DataColumn column in table.Columns)
            {
                Console.Write("\table " + row[column] );
            }
            Console.WriteLine();
        }
    }
}

Remarks

The Merge method is used to merge two DataSet objects that have largely similar schemas. A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. This allows the client application to have a refreshed DataSet with the latest data from the data source.

The Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

In a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. In this scenario, the GetChanges method is first invoked. That method returns a second DataSet optimized for validating and merging. This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. The middle-tier component then updates the original data source with the changes through stored procedures. The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

To facilitate explanation of the Merge method, we use "target" to signify the current DataSet, and "source" to name the second (parameter) DataSet. The target DataSet is so named because it is the object upon which an action (the merge) occurs. The second DataSet is called a "source" because the information it contains does not change, but instead is merged into the current DataSet.

When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. In that case, the merged DataSet contains the added schema and data.

After merging schemas, the data is merged.

When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

During a merge, constraints are disabled. If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. The errors must be resolved before attempting to reset the EnforceConstraints property to true.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Merge(DataTable, Boolean, MissingSchemaAction)

Source:
DataSet.cs
Source:
DataSet.cs
Source:
DataSet.cs

Merges a specified DataTable and its schema into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

C#
public void Merge(System.Data.DataTable table, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction);

Parameters

table
DataTable

The DataTable whose data and schema will be merged.

preserveChanges
Boolean

One of the MissingSchemaAction values.

missingSchemaAction
MissingSchemaAction

true to preserve changes in the DataSet; otherwise, false.

Exceptions

The table is null.

Examples

The following example creates a simple DataSet with one table, two columns, and ten rows. A second DataTable is created that is nearly identical to the first except that a new DataColumn is added to the table. Two rows are added to the second table, which is then merged into the DataSet with the preserveChanges argument set to false, and the missingSchemaAction argument set to MissingSchemaAction.Add.

C#
private void DemonstrateMergeTableAddSchema()
{
    // Create a DataSet with one table, two columns, and ten rows.
    DataSet dataSet = new DataSet("dataSet");
    DataTable table = new DataTable("Items");

    // Add table to the DataSet
    dataSet.Tables.Add(table);

    // Create and add two columns to the DataTable
    DataColumn idColumn = new DataColumn("id",
        Type.GetType("System.Int32"),"");
    idColumn.AutoIncrement=true;
    DataColumn itemColumn = new DataColumn("Item",
        Type.GetType("System.Int32"),"");
    table.Columns.Add(idColumn);
    table.Columns.Add(itemColumn);

    // Set the primary key to the first column.
    table.PrimaryKey = new DataColumn[1]{ idColumn };

    // Add RowChanged event handler for the table.
    table.RowChanged+= new DataRowChangeEventHandler(Row_Changed);

    // Add ten rows.
    for(int i = 0; i <10;i++)
    {
        DataRow row=table.NewRow();
        row["Item"]= i;
        table.Rows.Add(row);
    }

    // Accept changes.
    dataSet.AcceptChanges();
    PrintValues(dataSet, "Original values");

    // Create a second DataTable identical to the first, with
    // one extra column using the Clone method.
    DataTable cloneTable = table.Clone();
    cloneTable.Columns.Add("extra", typeof(string));

    // Add two rows. Note that the id column can'table be the
    // same as existing rows in the DataSet table.
    DataRow newRow;
    newRow=cloneTable.NewRow();
    newRow["id"]= 12;
    newRow["Item"]=555;
    newRow["extra"]= "extra Column 1";
    cloneTable.Rows.Add(newRow);

    newRow=cloneTable.NewRow();
    newRow["id"]= 13;
    newRow["Item"]=665;
    newRow["extra"]= "extra Column 2";
    cloneTable.Rows.Add(newRow);

    // Merge the table into the DataSet.
    Console.WriteLine("Merging");
    dataSet.Merge(cloneTable,false,MissingSchemaAction.Add);
    PrintValues(dataSet, "Merged With Table, Schema Added");
}

private void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row Changed " + e.Action.ToString()
        + "\table" + e.Row.ItemArray[0]);
}

private void PrintValues(DataSet dataSet, string label)
{
    Console.WriteLine("\n" + label);
    foreach(DataTable table in dataSet.Tables)
    {
        Console.WriteLine("TableName: " + table.TableName);
        foreach(DataRow row in table.Rows)
        {
            foreach(DataColumn column in table.Columns)
            {
                Console.Write("\table " + row[column] );
            }
            Console.WriteLine();
        }
    }
}

Remarks

The Merge method is used to merge two DataSet objects that have largely similar schemas. A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataSet. This allows the client application to have a refreshed DataSet with the latest data from the data source.

The Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataSet.

iOn a client application, it is common to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle-tier component. In this scenario, the GetChanges method is first invoked. That method returns a second DataSet optimized for validating and merging. This second DataSet object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataSet. This subset is generally smaller, and thus more efficiently passed back to a middle-tier component. The middle-tier component then updates the original data source with the changes through stored procedures. The middle tier can then send back either a new DataSet that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataSet can be merged back into the client application's original DataSet with the Merge method.

When the Merge method is called, the schemas of the two DataSet objects are compared because it is possible that the schemas may have been changed. For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. If the source DataSet contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. In that case, the merged DataSet contains the added schema and data.

After merging schemas, the data is merged.

When merging a new source DataSet into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

During a merge, constraints are disabled. If any constraints cannot be enabled at the end of merge, a ConstraintException is generated and the merged data is retained while the constraints are disabled. In this case, the EnforceConstraints property is set to false, and all rows that are invalid are marked in error. The errors must be resolved before attempting to reset the EnforceConstraints property to true.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1