DataTable.Merge 方法

定义

将指定的 DataTable 与当前 DataTable 合并。

重载

Merge(DataTable, Boolean, MissingSchemaAction)

将指定的 DataTable 与当前 DataTable 合并,指示是否保留更改以及如何处理当前 DataTable 中缺失的架构。

Merge(DataTable, Boolean)

将指定的 DataTable 与当前 DataTable 合并,指示是否保留当前 DataTable 中的更改。

Merge(DataTable)

将指定的 DataTable 与当前 DataTable 合并。

示例

以下控制台应用程序演示了 方法的 missingSchemaAction 参数 Merge 的行为。 此示例创建同一表的两个版本,修改第二个版本的架构。 然后,代码尝试将第二个表合并到第一个表中。

注意

此示例演示如何使用 Merge 的重载版本之一。 有关可能可用的其他示例,请参阅各个重载主题。

private static void DemonstrateMergeTable()
{
    DataTable table1 = new DataTable("Items");

    // Add columns
    DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
    DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));
    table1.Columns.Add(idColumn);
    table1.Columns.Add(itemColumn);

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { idColumn };

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

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
    {
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;
        table1.Rows.Add(row);
    }

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

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add column to the second column, so that the
    // schemas no longer match.
    table2.Columns.Add("newColumn", typeof(System.String));

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    row["newColumn"] = "new column 1";
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    row["newColumn"] = "new column 2";
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    row["newColumn"] = "new column 3";
    table2.Rows.Add(row);

    // Merge table2 into the table1.
    Console.WriteLine("Merging");
    table1.Merge(table2, false, MissingSchemaAction.Add);
    PrintValues(table1, "Merged With table1, schema added");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}", e.Action,
        e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim table1 As New DataTable("Items")

  ' Add columns
  Dim idColumn As New DataColumn("id", GetType(System.Int32))
  Dim itemColumn As New DataColumn("item", GetType(System.Int32))
  table1.Columns.Add(idColumn)
  table1.Columns.Add(itemColumn)

  ' Set the primary key column.
  table1.PrimaryKey = New DataColumn() {idColumn}

  ' Add RowChanged event handler for the table.
  AddHandler table1.RowChanged, AddressOf Row_Changed

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("id") = i
    row("item") = i
    table1.Rows.Add(row)
  Next i

  ' Accept changes.
  table1.AcceptChanges()
  PrintValues(table1, "Original values")

  ' Create a second DataTable identical to the first.
  Dim table2 As DataTable = table1.Clone()

  ' Add column to the second column, so that the 
  ' schemas no longer match.
  table2.Columns.Add("newColumn", GetType(System.String))

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = table2.NewRow()
  row("id") = 14
  row("item") = 774
  row("newColumn") = "new column 1"
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 12
  row("item") = 555
  row("newColumn") = "new column 2"
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 13
  row("item") = 665
  row("newColumn") = "new column 3"
  table2.Rows.Add(row)

  ' Merge table2 into the table1.
  Console.WriteLine("Merging")
  table1.Merge(table2, False, MissingSchemaAction.Add)
  PrintValues(table1, "Merged With table1, Schema added")
End Sub

Private Sub Row_Changed(ByVal sender As Object, _
      ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, _
      ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注解

方法 Merge 用于合并架构大致相似的两 DataTable 个对象。 合并通常用于客户端应用程序,以将数据源的最新更改合并到现有 DataTable中。 这样,客户端应用程序就可以使用数据源中的最新数据刷新 DataTable

合并操作仅考虑原始表和要合并的表。 子表不受影响或不包含子表。 如果表具有一个或多个子表(定义为关系的一部分),则必须单独合并每个子表。

Merge(DataTable, Boolean, MissingSchemaAction)

Source:
DataTable.cs
Source:
DataTable.cs
Source:
DataTable.cs

将指定的 DataTable 与当前 DataTable 合并,指示是否保留更改以及如何处理当前 DataTable 中缺失的架构。

public:
 void Merge(System::Data::DataTable ^ table, bool preserveChanges, System::Data::MissingSchemaAction missingSchemaAction);
public void Merge (System.Data.DataTable table, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction);
member this.Merge : System.Data.DataTable * bool * System.Data.MissingSchemaAction -> unit
Public Sub Merge (table As DataTable, preserveChanges As Boolean, missingSchemaAction As MissingSchemaAction)

参数

table
DataTable

要与当前 DataTable 合并的 DataTable

preserveChanges
Boolean

如果保留当前 DataTable 中的更改,则为 true;否则为 false

missingSchemaAction
MissingSchemaAction

MissingSchemaAction 值之一。

示例

以下控制台应用程序演示了 方法的 missingSchemaAction 参数 Merge 的行为。 此示例创建同一表的两个版本,修改第二个版本的架构。 然后,代码尝试将第二个表合并到第一个表中。

private static void DemonstrateMergeTable()
{
    DataTable itemsTable = new DataTable("Items");

    // Add columns
    DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
    DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));
    itemsTable.Columns.Add(idColumn);
    itemsTable.Columns.Add(itemColumn);

    // Set the primary key column.
    itemsTable.PrimaryKey = new DataColumn[] { idColumn };

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

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
    {
        row = itemsTable.NewRow();
        row["id"] = i;
        row["item"] = i;
        itemsTable.Rows.Add(row);
    }

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

    // Create a second DataTable identical to the first.
    DataTable itemsClone = itemsTable.Clone();

    // Add column to the second column, so that the
    // schemas no longer match.
    itemsClone.Columns.Add("newColumn", typeof(System.String));

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = itemsClone.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    row["newColumn"] = "new column 1";
    itemsClone.Rows.Add(row);

    row = itemsClone.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    row["newColumn"] = "new column 2";
    itemsClone.Rows.Add(row);

    row = itemsClone.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    row["newColumn"] = "new column 3";
    itemsClone.Rows.Add(row);

    // Merge itemsClone into the itemsTable.
    Console.WriteLine("Merging");
    itemsTable.Merge(itemsClone, false, MissingSchemaAction.Add);
    PrintValues(itemsTable, "Merged With itemsTable, schema added");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}",
        e.Action, e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim itemsTable As New DataTable("Items")

  ' Add columns
  Dim idColumn As New DataColumn("id", GetType(System.Int32))
  Dim itemColumn As New DataColumn("item", GetType(System.Int32))
  itemsTable.Columns.Add(idColumn)
  itemsTable.Columns.Add(itemColumn)

  ' Set the primary key column.
  itemsTable.PrimaryKey = New DataColumn() {idColumn}

  ' Add RowChanged event handler for the table.
  AddHandler itemsTable.RowChanged, AddressOf Row_Changed

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = itemsTable.NewRow()
    row("id") = i
    row("item") = i
    itemsTable.Rows.Add(row)
  Next i

  ' Accept changes.
  itemsTable.AcceptChanges()
  PrintValues(itemsTable, "Original values")

  ' Create a second DataTable identical to the first.
  Dim itemsClone As DataTable = itemsTable.Clone()

  ' Add column to the second column, so that the 
  ' schemas no longer match.
  itemsClone.Columns.Add("newColumn", GetType(System.String))

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = itemsClone.NewRow()
  row("id") = 14
  row("item") = 774
  row("newColumn") = "new column 1"
  itemsClone.Rows.Add(row)

  row = itemsClone.NewRow()
  row("id") = 12
  row("item") = 555
  row("newColumn") = "new column 2"
  itemsClone.Rows.Add(row)

  row = itemsClone.NewRow()
  row("id") = 13
  row("item") = 665
  row("newColumn") = "new column 3"
  itemsClone.Rows.Add(row)

  ' Merge itemsClone into the itemsTable.
  Console.WriteLine("Merging")
  itemsTable.Merge(itemsClone, False, MissingSchemaAction.Add)
  PrintValues(itemsTable, "Merged With itemsTable, Schema added")
End Sub

Private Sub Row_Changed(ByVal sender As Object, _
  ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注解

方法 Merge 用于合并架构大致相似的两 DataTable 个对象。 合并通常用于客户端应用程序,以将数据源的最新更改合并到现有 DataTable中。 这样,客户端应用程序就可以使用数据源中的最新数据刷新 DataTable

合并操作仅考虑原始表和要合并的表。 子表不受影响或不包含子表。 如果表具有一个或多个子表(定义为关系的一部分),则必须单独合并每个子表。

Merge方法通常在一系列过程结束时调用,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataTable

执行合并时,除非开发人员为 参数指定 false,否则在合并操作期间将保留合并之前对 preserveChanges 现有数据所做的更改。 如果 参数 preserveChanges 设置为 true,则传入值不会覆盖现有行的当前行版本中的现有值。 如果 参数 preserveChanges 设置为 false,则传入值会覆盖现有行的当前行版本中的现有值。 有关行版本的详细信息,请参阅行状态和行版本

在客户端应用程序中,通常有一个用户可以单击的按钮,用于收集更改的数据并对其进行验证,然后再将其发送回中间层组件。 在此方案中, GetChanges 首先调用 方法。 该方法返回针对验证和合并进行优化的第二 DataTable 个。 第二 DataTable 个 对象仅 DataTable 包含已更改的 和 DataRow 对象,从而生成原始 DataTable的子集。 此子集通常较小,因此,此子集可以更有效地传递回中间层组件。 然后,中间层组件通过存储过程使用更改更新原始数据源。 然后,中间层可以通过) 再次运行原始查询,发送回包含原始数据和数据源 (的最新数据的新 DataTable 数据,也可以通过数据源对子集所做的任何更改发送回该子集。 (例如,如果数据源自动创建唯一主键值,则可以将这些值传播回客户端应用程序。) 无论哪种情况,返回DataTable的 都可以使用 Merge 方法合并回客户端应用程序的原始DataTable值。

Merge调用 方法时,将比较两DataTable个 对象的架构,因为架构可能已更改。 例如,在企业到企业方案中,新列可能已通过自动化过程添加到 XML 架构中。 如果源 DataTable 包含架构元素 (目标中缺少) 添加 DataColumn 的对象,则可以通过将 参数设置为 missingSchemaActionMissingSchemaAction.Add来将架构元素添加到目标中。 在这种情况下,合并 DataTable 的 包含添加的架构和数据。

合并架构后,数据将合并。

将新源DataTable合并到目标中时,任何值为 、 ModifiedDeletedUnchanged源行DataRowState将与具有相同主键值的目标行匹配。 值为 的Added源行DataRowState与与新源行具有相同主键值的新目标行匹配。

另请参阅

适用于

Merge(DataTable, Boolean)

Source:
DataTable.cs
Source:
DataTable.cs
Source:
DataTable.cs

将指定的 DataTable 与当前 DataTable 合并,指示是否保留当前 DataTable 中的更改。

public:
 void Merge(System::Data::DataTable ^ table, bool preserveChanges);
public void Merge (System.Data.DataTable table, bool preserveChanges);
member this.Merge : System.Data.DataTable * bool -> unit
Public Sub Merge (table As DataTable, preserveChanges As Boolean)

参数

table
DataTable

要与当前 DataTable 合并的 DataTable

preserveChanges
Boolean

如果保留当前 DataTable 中的更改,则为 true;否则为 false

示例

以下控制台应用程序创建包含 DataTable 行,修改这些行中的某些数据,并尝试合并其他 DataTable中的数据。 该示例演示 参数的不同行为 preserveChanges


private static void DemonstrateMergeTable()
{
    // Demonstrate merging, within and without
    // preserving changes.

    // In this example, take these actions:
    // 1. Create a DataTable (table1) and fill the table with data.
    // 2. Create a copy of table1, and modify its data (modifiedTable).
    // 3. Modify data in table1.
    // 4. Make a copy of table1 (table1Copy).
    // 5. Merge the data from modifiedTable into table1 and table1Copy,
    //    showing the difference between setting the preserveChanges
    //    parameter to true and false.

    // Create a new DataTable.
    DataTable table1 = new DataTable("Items");

    // Add two columns to the table:
    DataColumn column = new DataColumn("id", typeof(System.Int32));
    column.AutoIncrement = true;
    table1.Columns.Add(column);

    column = new DataColumn("item", typeof(System.String));
    table1.Columns.Add(column);

    // Set primary key column.
    table1.PrimaryKey = new DataColumn[] { table1.Columns[0] };

    // Add some rows.
    DataRow row;
    for (int i = 0; i <= 3; i++)
    {
        row = table1.NewRow();
        row["item"] = "Item " + i;
        table1.Rows.Add(row);
    }

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

    // Using the same schema as the original table,
    // modify the data for later merge.
    DataTable modifiedTable = table1.Copy();
    foreach (DataRow rowModified in modifiedTable.Rows)
    {
        rowModified["item"] = rowModified["item"].ToString()
            + " modified";
    }
    modifiedTable.AcceptChanges();

    // Change row values, and add a new row:
    table1.Rows[0]["item"] = "new Item 0";
    table1.Rows[1]["item"] = "new Item 1";

    row = table1.NewRow();
    row["id"] = 4;
    row["item"] = "Item 4";
    table1.Rows.Add(row);

    // Get a copy of the modified data:
    DataTable table1Copy = table1.Copy();
    PrintValues(table1, "Modified and new Values");
    PrintValues(modifiedTable, "Data to be merged into table1");

    // Merge new data into the modified data.
    table1.Merge(modifiedTable, true);
    PrintValues(table1, "Merged data (preserve changes)");

    table1Copy.Merge(modifiedTable, false);
    PrintValues(table1Copy, "Merged data (don't preserve changes)");
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            Console.Write("\t{0}", row[column, DataRowVersion.Current]);
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  ' Demonstrate merging, within and without
  ' preserving changes.

  ' In this example, take these actions:
  ' 1. Create a DataTable (table1) and fill the table with data.
  ' 2. Create a copy of table1, and modify its data (modifiedTable).
  ' 3. Modify data in table1.
  ' 4. Make a copy of table1 (table1Copy).
  ' 5. Merge the data from modifiedTable into table1 and table1Copy, 
  '    showing the difference between setting the preserveChanges 
  '    parameter to true and false.

  ' Create a new DataTable.
  Dim table1 As New DataTable("Items")

  ' Add two columns to the table:
  Dim column As New DataColumn("id", GetType(System.Int32))
  column.AutoIncrement = True
  table1.Columns.Add(column)

  column = New DataColumn("item", GetType(System.String))
  table1.Columns.Add(column)

  ' Set primary key column.
  table1.PrimaryKey = New DataColumn() {table1.Columns(0)}

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("item") = "Item " & i
    table1.Rows.Add(row)
  Next i

  ' Accept changes.
  table1.AcceptChanges()
  PrintValues(table1, "Original values")

  ' Using the same schema as the original table, 
  ' modify the data for later merge.
  Dim modifiedTable As DataTable = table1.Copy()
  For Each row In modifiedTable.Rows
    row("item") = row("item").ToString() & " modified"
  Next
  modifiedTable.AcceptChanges()

  ' Change row values, and add a new row:
  table1.Rows(0)("item") = "New Item 0"
  table1.Rows(1)("item") = "New Item 1"

  row = table1.NewRow()
  row("id") = 4
  row("item") = "Item 4"
  table1.Rows.Add(row)

  ' Get a copy of the modified data:
  Dim table1Copy As DataTable = table1.Copy()
  PrintValues(table1, "Modified and New Values")
  PrintValues(modifiedTable, "Data to be merged into table1")


  ' Merge new data into the modified data.
  table1.Merge(modifiedTable, True)
  PrintValues(table1, "Merged data (preserve changes)")

  table1Copy.Merge(modifiedTable, False)
  PrintValues(table1Copy, "Merged data (don't preserve changes)")

End Sub

Private Sub PrintValues(ByVal table As DataTable, _
  ByVal label As String)

  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each column As DataColumn In table.Columns
      Console.Write("{0}{1}", ControlChars.Tab, row(column, _
          DataRowVersion.Current))
    Next column
    Console.WriteLine()
  Next row
End Sub

注解

Merge 方法用于合并具有大致相似架构的两 DataTable 个对象。 合并通常用于客户端应用程序,以将数据源的最新更改合并到现有 DataTable中。 这样,客户端应用程序就可以使用数据源中的最新数据刷新 DataTable

合并操作仅考虑原始表和要合并的表。 子表不受影响或不包含子表。 如果表具有一个或多个子表(定义为关系的一部分),则必须单独合并每个子表。

Merge方法通常在一系列过程结束时调用,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataTable

执行合并时,除非开发人员为 参数指定 false,否则在合并操作期间将保留合并之前对 preserveChanges 现有数据所做的更改。 如果 参数 preserveChanges 设置为 true,则传入值不会覆盖现有行的当前行版本中的现有值。 如果 参数 preserveChanges 设置为 false,则传入值会覆盖现有行的当前行版本中的现有值。 有关行版本的详细信息,请参阅行状态和行版本

在客户端应用程序中,通常有一个用户可以单击的按钮,用于收集更改的数据并对其进行验证,然后再将其发送回中间层组件。 在此方案中, GetChanges 首先调用 方法。 该方法返回针对验证和合并进行优化的第二 DataTable 个。 第二 DataTable 个 对象仅 DataTable 包含已更改的 和 DataRow 对象,从而生成原始 DataTable的子集。 此子集通常较小,因此,此子集可以更有效地传递回中间层组件。 然后,中间层组件通过存储过程使用更改更新原始数据源。 然后,中间层可以通过) 再次运行原始查询,发送回包含原始数据和数据源 (的最新数据的新 DataTable 数据,也可以通过数据源对子集所做的任何更改发送回该子集。 (例如,如果数据源自动创建唯一主键值,则可以将这些值传播回客户端应用程序。) 无论哪种情况,返回DataTable的 都可以使用 Merge 方法合并回客户端应用程序的原始DataTable值。

将新源DataTable合并到目标中时,任何值为 、 ModifiedDeletedUnchanged源行DataRowState将与具有相同主键值的目标行匹配。 值为 的Added源行DataRowState与与新源行具有相同主键值的新目标行匹配。

另请参阅

适用于

Merge(DataTable)

Source:
DataTable.cs
Source:
DataTable.cs
Source:
DataTable.cs

将指定的 DataTable 与当前 DataTable 合并。

public:
 void Merge(System::Data::DataTable ^ table);
public void Merge (System.Data.DataTable table);
member this.Merge : System.Data.DataTable -> unit
Public Sub Merge (table As DataTable)

参数

table
DataTable

要与当前 DataTable 合并的 DataTable

示例

以下控制台应用程序创建一个简单的 DataTable ,并将数据添加到表中。 然后,该示例创建表的副本,并将行添加到该副本。 最后,该示例调用 Merge 方法,将第二个表中的数据与第一个表中的数据合并。

private static void DemonstrateMergeTable()
{
    DataTable table1 = new DataTable("Items");

    // Add columns
    DataColumn column1 = new DataColumn("id", typeof(System.Int32));
    DataColumn column2 = new DataColumn("item", typeof(System.Int32));
    table1.Columns.Add(column1);
    table1.Columns.Add(column2);

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { column1 };

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

    // Add some rows.
    DataRow row;
    for (int i = 0; i <= 3; i++)
    {
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;
        table1.Rows.Add(row);
    }

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

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    table2.Rows.Add(row);

    // Merge table2 into the table1.
    Console.WriteLine("Merging");
    table1.Merge(table2);
    PrintValues(table1, "Merged With table1");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}",
        e.Action, e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim table1 As New DataTable("Items")

  ' Add columns
  Dim column1 As New DataColumn("id", GetType(System.Int32))
  Dim column2 As New DataColumn("item", GetType(System.Int32))
  table1.Columns.Add(column1)
  table1.Columns.Add(column2)

  ' Set the primary key column.
  table1.PrimaryKey = New DataColumn() {column1}

  ' Add RowChanged event handler for the table.
  AddHandler table1.RowChanged, AddressOf Row_Changed

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("id") = i
    row("item") = i
    table1.Rows.Add(row)
  Next i

  ' Accept changes.
  table1.AcceptChanges()
  PrintValues(table1, "Original values")

  ' Create a second DataTable identical to the first.
  Dim table2 As DataTable = table1.Clone()

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = table2.NewRow()
  row("id") = 14
  row("item") = 774
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 12
  row("item") = 555
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 13
  row("item") = 665
  table2.Rows.Add(row)

  ' Merge table2 into the table1.
  Console.WriteLine("Merging")
  table1.Merge(table2)
  PrintValues(table1, "Merged With table1")

End Sub

Private Sub Row_Changed(ByVal sender As Object, _
  ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, _
  ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注解

Merge 方法用于合并具有大致相似架构的两 DataTable 个对象。 合并通常用于客户端应用程序,以将数据源的最新更改合并到现有 DataTable中。 这样,客户端应用程序就可以使用数据源中的最新数据刷新 DataTable

合并操作仅考虑原始表和要合并的表。 子表不受影响或不包含子表。 如果表具有一个或多个子表(定义为关系的一部分),则必须单独合并每个子表。

Merge方法通常在一系列过程结束时调用,这些过程涉及验证更改、协调错误、使用更改更新数据源,最后刷新现有 DataTable

执行合并时,合并操作期间默认保留合并前对现有数据所做的更改。 开发人员可以通过调用此方法的另外两个重载之一并为 参数指定 false 值 preserveChanges 来修改此行为。

在客户端应用程序中,通常有一个用户可以单击的按钮,用于收集更改的数据并对其进行验证,然后再将其发送回中间层组件。 在此方案中, GetChanges 首先调用 方法。 该方法返回针对验证和合并进行优化的第二 DataTable 个。 第二 DataTable 个对象仅 DataRow 包含已更改的对象,从而生成原始 DataTable的子集。 此子集通常较小,因此可以更有效地传递回中间层组件。 然后,中间层组件通过存储过程使用更改更新原始数据源。 然后,中间层可以通过) 再次运行原始查询,发送回包含原始数据和数据源 (的最新数据的新 DataTable 数据,也可以通过数据源对子集所做的任何更改发送回该子集。 (例如,如果数据源自动创建唯一主键值,则可以将这些值传播回客户端应用程序。) 无论哪种情况,返回DataTable的 都可以使用 Merge 方法合并回客户端应用程序的原始DataTable值。

将新源DataTable合并到目标中时,任何值为 UnchangedModifiedDeleted的源行DataRowState都与具有相同主键值的目标行匹配。 值为 的Added源行DataRowState与主键值与新源行相同的新目标行匹配。

另请参阅

适用于