DataTable.Merge 方法

定義

將指定的 DataTable 與目前的 DataTable 合併。

多載

Merge(DataTable, Boolean, MissingSchemaAction)

合併指定的 DataTable 與目前的 DataTable,指出是否保留變更,以及如何處理目前在 DataTable 中缺少的結構描述。

Merge(DataTable, Boolean)

合併指定的 DataTable 與目前的 DataTable,指出是否保留目前 DataTable 中的變更。

Merge(DataTable)

將指定的 DataTable 與目前的 DataTable 合併。

範例

下列主控台應用程式示範 方法之 參數Merge的行為missingSchemaAction。 本範例會建立兩個相同數據表的版本,修改第二個版本的架構。 然後,程式代碼會嘗試將第二個數據表合併到第一個數據表。

注意

此範例示範如何使用其中一個多載版本的 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)

來源:
DataTable.cs
來源:
DataTable.cs
來源:
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

若要保留目前 true 中的變更,則為 DataTable,否則為 false

missingSchemaAction
MissingSchemaAction

其中一個 MissingSchemaAction 值。

範例

下列主控台應用程式示範 方法之 參數Merge的行為missingSchemaAction。 本範例會建立兩個相同數據表的版本,修改第二個版本的架構。 然後,程式代碼會嘗試將第二個數據表合併到第一個數據表。

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

執行合併時,除非開發人員為 preserveChanges 參數指定 false,否則合併作業期間會保留對現有數據所做的變更。 preserveChanges如果 參數設定true為 ,傳入值不會覆寫現有數據列目前數據列版本中的現有值。 preserveChanges如果 參數設定false為 ,傳入值會覆寫現有數據列目前數據列版本中的現有值。 如需資料列版本的詳細資訊,請參閱資料 列狀態和資料列版本

在用戶端應用程式中,使用者通常會按兩下單一按鈕來收集已變更的數據,並在將它傳回仲介層元件之前加以驗證。 在此案例中,會 GetChanges 先叫用 方法。 該方法會傳回第二 DataTable 個優化來驗證和合併。 第二 DataTable 個物件只包含已變更的 DataTableDataRow 對象,導致原始 DataTable的子集。 此子集通常較小,因此此子集更有效率地傳回仲介層元件。 中間層元件接著會透過預存程式變更來更新原始數據源。 中間層接著可以再次執行原始查詢 () 執行原始查詢,以傳回 DataTable 包含原始數據和數據源的最新數據,也可以從數據源傳送任何已進行變更的子集。 (例如,如果數據源自動建立唯一的主鍵值,這些值可以傳播回用戶端應用程式。) 在任一情況下,傳回 DataTable 的 可以合併回用戶端應用程式的原始 DataTable 值與 Merge 方法。

Merge呼叫 方法時,會比較兩DataTable個對象的架構,因為架構可能已經變更。 例如,在企業對企業案例中,新的數據行可能已由自動化程式新增至 XML 架構。 如果來源DataTable包含架構元素 (新增DataColumn物件) 目標中遺漏的物件,則可以將自變數設定為 MissingSchemaAction.Add,將 自變數新增missingSchemaAction至目標。 在此情況下,合併 DataTable 的 包含新增的架構和數據。

合併架構之後,數據會合併。

將新來源合併至目標時,任何值為、 或 的來源DataTable數據列DataRowState,都Deleted與具有相同主鍵值的目標數據列Modified相符。Unchanged 具有 DataRowStateAdded 的來源數據列會比對與新源數據列相同的主鍵值的新目標數據列。

另請參閱

適用於

Merge(DataTable, Boolean)

來源:
DataTable.cs
來源:
DataTable.cs
來源:
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

若要保留目前 true 中的變更,則為 DataTable,否則為 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

執行合併時,除非開發人員為 preserveChanges 參數指定 false,否則合併作業期間會保留對現有數據所做的變更。 preserveChanges如果 參數設定true為 ,傳入值不會覆寫現有數據列目前數據列版本中的現有值。 preserveChanges如果 參數設定false為 ,傳入值會覆寫現有數據列目前數據列版本中的現有值。 如需資料列版本的詳細資訊,請參閱資料 列狀態和資料列版本

在用戶端應用程式中,使用者通常會按兩下單一按鈕來收集已變更的數據,並在將它傳回仲介層元件之前加以驗證。 在此案例中,會 GetChanges 先叫用 方法。 該方法會傳回第二 DataTable 個優化來驗證和合併。 第二 DataTable 個物件只包含已變更的 DataTableDataRow 對象,導致原始 DataTable的子集。 此子集通常較小,因此此子集更有效率地傳回仲介層元件。 中間層元件接著會透過預存程式變更來更新原始數據源。 中間層接著可以再次執行原始查詢 () 執行原始查詢,以傳回 DataTable 包含原始數據和數據源的最新數據,也可以從數據源傳送任何已進行變更的子集。 (例如,如果數據源自動建立唯一的主鍵值,這些值可以傳播回用戶端應用程式。) 在任一情況下,傳回 DataTable 的 可以合併回用戶端應用程式的原始 DataTable 值與 Merge 方法。

將新來源合併至目標時,任何值為、 或 的來源DataTable數據列DataRowState,都Deleted與具有相同主鍵值的目標數據列Modified相符。Unchanged 具有 DataRowStateAdded 的來源數據列會比對與新源數據列相同的主鍵值的新目標數據列。

另請參閱

適用於

Merge(DataTable)

來源:
DataTable.cs
來源:
DataTable.cs
來源:
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

執行合併時,合併作業期間預設會保留合併之前對現有數據的變更。 開發人員可以呼叫此方法的其他兩個多載之一,並指定參數的 preserveChanges false 值來修改此行為。

在用戶端應用程式中,使用者通常會按兩下單一按鈕來收集已變更的數據,並在將它傳回仲介層元件之前加以驗證。 在此案例中,會 GetChanges 先叫用 方法。 該方法會傳回第二 DataTable 個優化來驗證和合併。 第二 DataTable 個物件只 DataRow 包含已變更的物件,導致原始 DataTable的子集。 此子集通常較小,因此更有效率地傳回仲介層元件。 中間層元件接著會透過預存程式變更來更新原始數據源。 中間層接著可以再次執行原始查詢 () 執行原始查詢,以傳回 DataTable 包含原始數據和數據源的最新數據,也可以從數據源傳送任何已進行變更的子集。 (例如,如果數據源自動建立唯一的主鍵值,這些值可以傳播回用戶端應用程式。) 在任一情況下,傳回 DataTable 的 可以合併回用戶端應用程式的原始 DataTable 值與 Merge 方法。

將新來源 DataTable 合併到目標時,任何值為 DataRowStateUnchangedModifiedDeleted的來源數據列,會與具有相同主鍵值的目標數據列進行比對。 具有 DataRowStateAdded 的來源數據列會與新主鍵值與新源數據列相同的新目標數據列進行比對。

另請參閱

適用於