Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Merge Method (DataSet)

DataSet.Merge Method (DataSet)

.NET Framework 1.1

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

[Visual Basic]
Overloads Public Sub Merge( _
   ByVal dataSet As DataSet _
)
[C#]
public void Merge(
 DataSet dataSet
);
[C++]
public: void Merge(
 DataSet* dataSet
);
[JScript]
public function Merge(
   dataSet : DataSet
);

Parameters

dataSet
The DataSet whose data and schema will be merged.

Exceptions

Exception Type Condition
ConstraintException One or more constraints cannot be enabled.
ArgumentNullException The dataSet is a null reference (Nothing in Visual Basic).

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 usual 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 will then update 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 will contain 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.

Example

[Visual Basic, C#, C++] The following example uses the GetChanges, Update, and Merge methods on a DataSet.

[Visual Basic] 
Private Sub DemonstrateMerge()
    ' Create a DataSet with one table, two columns, and three rows.
    Dim ds As New DataSet("myDataSet")
    Dim t As New DataTable("Items")
    Dim c1 As New DataColumn("id", Type.GetType("System.Int32"))
    c1.AutoIncrement = True
    Dim c2 As New DataColumn("Item", Type.GetType("System.Int32"))
    ' DataColumn array to set primary key.
    Dim keyCol(1) As DataColumn
    Dim r As DataRow
    ' Create variable for temporary DataSet. 
    Dim xSet As DataSet
    ' Add columns to table, and table to DataSet.   
    t.Columns.Add(c1)
    t.Columns.Add(c2)
    ds.Tables.Add(t)
    ' Set primary key column.
    keyCol(0) = c1
    t.PrimaryKey = keyCol
    ' Add ten rows.
    Dim i As Integer
    For i = 0 To 9
        r = t.NewRow()
        r("Item") = i
        t.Rows.Add(r)
    Next i
    ' Accept changes.
    ds.AcceptChanges()
    PrintValues(ds, "Original values")
    ' Change two row values.
    t.Rows(0)("Item") = 50
    t.Rows(1)("Item") = 111
    ' Add one row.
    r = t.NewRow()
    r("Item") = 74
    t.Rows.Add(r)
    ' Insert code for error checking. Here we set one row in error.
    t.Rows(1).RowError = "over 100"
    PrintValues(ds, "Modified and New Values")
    ' If the table has changes or errors, create a subset DataSet.
    If ds.HasChanges(DataRowState.Modified Or DataRowState.Added) _
       And ds.HasErrors Then
        ' Use GetChanges to extract subset.
        xSet = ds.GetChanges(DataRowState.Modified Or DataRowState.Added)
        PrintValues(xSet, "Subset values")
        ' Insert code to reconcile errors. In this case, we'll reject changes.
        Dim xTable As DataTable
        For Each xTable In  xSet.Tables
            If xTable.HasErrors Then
                Dim xRow As DataRow
                For Each xRow In  xTable.Rows
                    'Console.WriteLine(xRow["Item"]);
                    If CInt(xRow("Item", DataRowVersion.Current)) > 100 Then
                        xRow.RejectChanges()
                        xRow.ClearErrors()
                    End If
                Next xRow
            End If
        Next xTable
        PrintValues(xSet, "Reconciled subset values")
        ' Merge changes back to first DataSet.
        ds.Merge(xSet)
        PrintValues(ds, "Merged Values")
    End If
End Sub

Private Sub PrintValues(ds As DataSet, label As String)
    Console.WriteLine(ControlChars.Cr + label)
    Dim t As DataTable
    For Each t In  ds.Tables
        Console.WriteLine("TableName: " + t.TableName)
        Dim r As DataRow
        For Each r In  t.Rows
            Dim c As DataColumn
            For Each c In  t.Columns
                Console.Write(ControlChars.Tab + " " + r(c).ToString())
            Next c
            Console.WriteLine()
        Next r
    Next t
End Sub

[C#] 
private void DemonstrateMerge() {
   // Create a DataSet with one table, two columns, and three rows.
   DataSet ds = new DataSet("myDataSet");
   DataTable t = new DataTable("Items");
   DataColumn c1 = new DataColumn("id", Type.GetType("System.Int32"));
   c1.AutoIncrement=true;
   DataColumn c2 = new DataColumn("Item", Type.GetType("System.Int32"));
   // DataColumn array to set primary key.
   DataColumn[] keyCol= new DataColumn[1];
   DataRow r;
   // Create variable for temporary DataSet. 
   DataSet xSet;
   // Add columns to table, and table to DataSet.   
   t.Columns.Add(c1);
   t.Columns.Add(c2);
   ds.Tables.Add(t);
   // Set primary key column.
   keyCol[0]= c1;
   t.PrimaryKey=keyCol;
   // Add ten rows.
   for(int i = 0; i <10;i++){
      r=t.NewRow();
      r["Item"]= i;
      t.Rows.Add(r);
   }
   // Accept changes.
   ds.AcceptChanges();
   PrintValues(ds, "Original values");
   // Change two row values.
   t.Rows[0]["Item"]= 50;
   t.Rows[1]["Item"]= 111;
   // Add one row.
   r=t.NewRow();
   r["Item"]=74;
   t.Rows.Add(r);
   // Insert code for error checking. Here we set one row in error.
   t.Rows[1].RowError= "over 100";
   PrintValues(ds, "Modified and New Values");
   // If the table has changes or errors, create a subset DataSet.
   if(ds.HasChanges(DataRowState.Modified | DataRowState.Added)& ds.HasErrors){
      // Use GetChanges to extract subset.
      xSet = ds.GetChanges(DataRowState.Modified|DataRowState.Added);
      PrintValues(xSet, "Subset values");
      // Insert code to reconcile errors. In this case, we'll reject changes.
      foreach(DataTable xTable in xSet.Tables){
         if (xTable.HasErrors){
            foreach(DataRow xRow in xTable.Rows){
            //Console.WriteLine(xRow["Item"]);
                 if((int)xRow["Item",DataRowVersion.Current ]> 100){
                  xRow.RejectChanges();
                  xRow.ClearErrors();
               }
            }
         }
      }
      PrintValues(xSet, "Reconciled subset values");
      // Merge changes back to first DataSet.
      ds.Merge(xSet);
      PrintValues(ds, "Merged Values");
   }
}

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();
      }
   }
}

[C++] 
private:
 void DemonstrateMerge() {
    // Create a DataSet with one table, two columns, and three rows.
    DataSet* ds = new DataSet(S"myDataSet");
    DataTable* t = new DataTable(S"Items");
    DataColumn* c1 = new DataColumn(S"id", Type::GetType(S"System.Int32"));
    c1->AutoIncrement=true;
    DataColumn* c2 = new DataColumn(S"Item", Type::GetType(S"System.Int32"));
    // DataColumn array to set primary key.
    DataColumn* keyCol[]= new DataColumn*[1];
    DataRow* r;
    // Create variable for temporary DataSet. 
    DataSet* xSet;
    // Add columns to table, and table to DataSet.   
    t->Columns->Add(c1);
    t->Columns->Add(c2);
    ds->Tables->Add(t);
    // Set primary key column.
    keyCol[0]= c1;
    t->PrimaryKey=keyCol;
    // Add ten rows.
    for(int i = 0; i <10;i++){
       r=t->NewRow();
       r->Item[S"Item"]= __box(i);
       t->Rows->Add(r);
    }
    // Accept changes.
    ds->AcceptChanges();
    PrintValues(ds, S"Original values");
    // Change two row values.
    t->Rows->Item[0]->Item[S"Item"]= __box(50);
    t->Rows->Item[1]->Item[S"Item"]= __box(111);
    // Add one row.
    r=t->NewRow();
    r->Item[S"Item"]=__box(74);
    t->Rows->Add(r);
    // Insert code for error checking. Here we set one row in error.
    t->Rows->Item[1]->RowError= S"over 100";
    PrintValues(ds, S"Modified and New Values");
    // If the table has changes or errors, create a subset DataSet.
    if(ds->HasChanges(static_cast<DataRowState>(DataRowState::Modified | DataRowState::Added))& ds->HasErrors){
       // Use GetChanges to extract subset.
       xSet = ds->GetChanges(static_cast<DataRowState>(DataRowState::Modified|DataRowState::Added));
       PrintValues(xSet, S"Subset values");
       // Insert code to reconcile errors. In this case, we'll reject changes.
       System::Collections::IEnumerator* myEnum = xSet->Tables->GetEnumerator();
       while (myEnum->MoveNext())
       {
          DataTable* xTable = __try_cast<DataTable*>(myEnum->Current);
          if (xTable->HasErrors){
             System::Collections::IEnumerator* myEnum1 = xTable->Rows->GetEnumerator();
             while (myEnum1->MoveNext())
             {
                DataRow* xRow = __try_cast<DataRow*>(myEnum1->Current);
             //Console.WriteLine(xRow["Item"]);
                  if(*__try_cast<Int32*>(xRow->get_Item(S"Item",DataRowVersion::Current))> 100){
                   xRow->RejectChanges();
                   xRow->ClearErrors();
                }
             }
          }
       }
       PrintValues(xSet, S"Reconciled subset values");
       // Merge changes back to first DataSet.
       ds->Merge(xSet);
       PrintValues(ds, S"Merged Values");
    }
 }

 void PrintValues(DataSet* ds, String* label){
    Console::WriteLine(S"\n{0}", label);
    System::Collections::IEnumerator* myEnum2 = ds->Tables->GetEnumerator();
    while (myEnum2->MoveNext())
    {
       DataTable* t = __try_cast<DataTable*>(myEnum2->Current);
       Console::WriteLine(S"TableName: {0}", t->TableName);
       System::Collections::IEnumerator* myEnum3 = t->Rows->GetEnumerator();
       while (myEnum3->MoveNext())
       {
          DataRow* r = __try_cast<DataRow*>(myEnum3->Current);
          System::Collections::IEnumerator* myEnum4 = t->Columns->GetEnumerator();
          while (myEnum4->MoveNext())
          {
             DataColumn* c = __try_cast<DataColumn*>(myEnum4->Current);
             Console::Write(S"\t {0}", r->Item[c] );
          }
          Console::WriteLine();
       }
    }
 }

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

DataSet Class | DataSet Members | System.Data Namespace | DataSet.Merge Overload List | ForeignKeyConstraint | GetChanges | UniqueConstraint

Show:
© 2015 Microsoft