共用方式為


DataTable.Load 方法

定義

利用提供的 IDataReader資料來源 來填入 aDataTable。 如果已經 DataTable 包含資料列,來自資料來源的輸入資料會與現有的資料列合併。

多載

名稱 Description
Load(IDataReader)

利用提供的 IDataReader資料來源 來填入 aDataTable。 如果已經 DataTable 包含資料列,來自資料來源的輸入資料會與現有的資料列合併。

Load(IDataReader, LoadOption)

利用提供的 IDataReader資料來源 來填入 aDataTable。 若已 DataTable 包含列數,則根據參數值 loadOption ,資料來源的輸入資料會與現有資料列合併。

Load(IDataReader, LoadOption, FillErrorEventHandler)

利用錯誤處理代理所提供的IDataReader資料,填DataTable入資料來源的值。

範例

以下範例展示了呼叫該 Load 方法時涉及的幾個問題。 首先,範例聚焦於結構問題,包括從已載 IDataReader入的結構推斷結構,接著處理不相容的結構,以及缺少或新增欄位的結構。 接著範例聚焦於資料議題,包括處理各種載入選項。

備註

此範例展示了如何使用其中一個超載版本的 Load。 其他可能可用的範例,請參閱個別超載主題。

static void Main()
{
    // This example examines a number of scenarios involving the
    // DataTable.Load method.
    Console.WriteLine("Load a DataTable and infer its schema:");

    // The table has no schema. The Load method will infer the
    // schema from the IDataReader:
    DataTable table = new DataTable();

    // Retrieve a data reader, based on the Customers data. In
    // an application, this data might be coming from a middle-tier
    // business object:
    DataTableReader reader = new DataTableReader(GetCustomers());

    table.Load(reader);
    PrintColumns(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine("Load a DataTable from an incompatible IDataReader:");

    // Create a table with a single integer column. Attempt
    // to load data from a reader with a schema that is
    // incompatible. Note the exception, determined
    // by the particular incompatibility:
    table = GetIntegerTable();
    reader = new DataTableReader(GetStringTable());
    try
    {
        table.Load(reader);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
    }

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable with an IDataReader that has extra columns:");

    // Note that loading a reader with extra columns adds
    // the columns to the existing table, if possible:
    table = GetIntegerTable();
    reader = new DataTableReader(GetCustomers());
    table.Load(reader);
    PrintColumns(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable with an IDataReader that has missing columns:");

    // Note that loading a reader with missing columns causes
    // the columns to be filled with null data, if possible:
    table = GetCustomers();
    reader = new DataTableReader(GetIntegerTable());
    table.Load(reader);
    PrintColumns(table);

    // Demonstrate the various possibilites when loading data into
    // a DataTable that already contains data.
    Console.WriteLine(" ============================= ");
    Console.WriteLine("Demonstrate data considerations:");
    Console.WriteLine("Current value, Original value, (RowState)");
    Console.WriteLine(" ============================= ");
    Console.WriteLine("Original table:");

    table = SetupModifiedRows();
    DisplayRowState(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine("Data in IDataReader to be loaded:");
    DisplayRowState(GetChangedCustomers());

    PerformDemo(LoadOption.OverwriteChanges);
    PerformDemo(LoadOption.PreserveChanges);
    PerformDemo(LoadOption.Upsert);

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static void DisplayRowState(DataTable table)
{
    for (int i = 0; i <= table.Rows.Count - 1; i++)
    {
        object current = "--";
        object original = "--";
        DataRowState rowState = table.Rows[i].RowState;

        // Attempt to retrieve the current value, which doesn't exist
        // for deleted rows:
        if (rowState != DataRowState.Deleted)
        {
            current = table.Rows[i]["Name", DataRowVersion.Current];
        }

        // Attempt to retrieve the original value, which doesn't exist
        // for added rows:
        if (rowState != DataRowState.Added)
        {
            original = table.Rows[i]["Name", DataRowVersion.Original];
        }
        Console.WriteLine("{0}: {1}, {2} ({3})", i, current,
            original, rowState);
    }
}

private static DataTable GetChangedCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

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

    table.Rows.Add(new object[] { 0, "XXX" });
    table.Rows.Add(new object[] { 1, "XXX" });
    table.Rows.Add(new object[] { 2, "XXX" });
    table.Rows.Add(new object[] { 3, "XXX" });
    table.Rows.Add(new object[] { 4, "XXX" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetCustomers()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

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

    table.Rows.Add(new object[] { 0, "Mary" });
    table.Rows.Add(new object[] { 1, "Andy" });
    table.Rows.Add(new object[] { 2, "Peter" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetIntegerTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));

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

    table.Rows.Add(new object[] { 4 });
    table.Rows.Add(new object[] { 5 });
    table.AcceptChanges();
    return table;
}

private static DataTable GetStringTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(string));

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

    table.Rows.Add(new object[] { "Mary" });
    table.Rows.Add(new object[] { "Andy" });
    table.Rows.Add(new object[] { "Peter" });
    table.AcceptChanges();
    return table;
}

private static void PerformDemo(LoadOption optionForLoad)
{

    // Load data into a DataTable, retrieve a DataTableReader containing
    // different data, and call the Load method. Depending on the
    // LoadOption value passed as a parameter, this procedure displays
    // different results in the DataTable.
    Console.WriteLine(" ============================= ");
    Console.WriteLine("table.Load(reader, {0})", optionForLoad);
    Console.WriteLine(" ============================= ");

    DataTable table = SetupModifiedRows();
    DataTableReader reader = new DataTableReader(GetChangedCustomers());
    table.RowChanging +=new DataRowChangeEventHandler(HandleRowChanging);

    table.Load(reader, optionForLoad);
    Console.WriteLine();
    DisplayRowState(table);
}

private static void PrintColumns(DataTable table)
{
    // Loop through all the rows in the DataTableReader
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i] + " ");
        }
        Console.WriteLine();
    }
}

private static DataTable SetupModifiedRows()
{
    // Fill a DataTable with customer info, and
    // then modify, delete, and add rows.

    DataTable table = GetCustomers();
    // Row 0 is unmodified.
    // Row 1 is modified.
    // Row 2 is deleted.
    // Row 3 is added.
    table.Rows[1]["Name"] = "Sydney";
    table.Rows[2].Delete();
    DataRow row = table.NewRow();
    row["ID"] = 3;
    row["Name"] = "Melony";
    table.Rows.Add(row);

    // Note that the code doesn't call
    // table.AcceptChanges()
    return table;
}

static void HandleRowChanging(object sender, DataRowChangeEventArgs e)
{
    Console.WriteLine(
        "RowChanging event: ID = {0}, action = {1}", e.Row["ID"],
        e.Action);
}
Sub Main()
  Dim table As New DataTable()

  ' This example examines a number of scenarios involving the 
  ' DataTable.Load method.
  Console.WriteLine("Load a DataTable and infer its schema:")

  ' Retrieve a data reader, based on the Customers data. In
  ' an application, this data might be coming from a middle-tier
  ' business object:
  Dim reader As New DataTableReader(GetCustomers())

  ' The table has no schema. The Load method will infer the 
  ' schema from the IDataReader:
  table.Load(reader)
  PrintColumns(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine("Load a DataTable from an incompatible IDataReader:")

  ' Create a table with a single integer column. Attempt
  ' to load data from a reader with a schema that is 
  ' incompatible. Note the exception, determined
  ' by the particular incompatibility:
  table = GetIntegerTable()
  reader = New DataTableReader(GetStringTable())
  Try
    table.Load(reader)
  Catch ex As Exception
    Console.WriteLine(ex.GetType.Name & ":" & ex.Message())
  End Try

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable with an IDataReader that has extra columns:")

  ' Note that loading a reader with extra columns adds
  ' the columns to the existing table, if possible:
  table = GetIntegerTable()
  reader = New DataTableReader(GetCustomers())
  table.Load(reader)
  PrintColumns(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable with an IDataReader that has missing columns:")

  ' Note that loading a reader with missing columns causes 
  ' the columns to be filled with null data, if possible:
  table = GetCustomers()
  reader = New DataTableReader(GetIntegerTable())
  table.Load(reader)
  PrintColumns(table)

  ' Demonstrate the various possibilites when loading data into
  ' a DataTable that already contains data.
  Console.WriteLine(" ============================= ")
  Console.WriteLine("Demonstrate data considerations:")
  Console.WriteLine("Current value, Original value, (RowState)")
  Console.WriteLine(" ============================= ")
  Console.WriteLine("Original table:")

  table = SetupModifiedRows()
  DisplayRowState(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine("Data in IDataReader to be loaded:")
  DisplayRowState(GetChangedCustomers())

  PerformDemo(LoadOption.OverwriteChanges)
  PerformDemo(LoadOption.PreserveChanges)
  PerformDemo(LoadOption.Upsert)

  Console.WriteLine("Press any key to continue.")
  Console.ReadKey()
End Sub

Private Sub DisplayRowState(ByVal table As DataTable)
  For i As Integer = 0 To table.Rows.Count - 1
    Dim current As Object = "--"
    Dim original As Object = "--"
    Dim rowState As DataRowState = table.Rows(i).RowState

    ' Attempt to retrieve the current value, which doesn't exist
    ' for deleted rows:
    If rowState <> DataRowState.Deleted Then
      current = table.Rows(i)("Name", DataRowVersion.Current)
    End If

    ' Attempt to retrieve the original value, which doesn't exist
    ' for added rows:
    If rowState <> DataRowState.Added Then
      original = table.Rows(i)("Name", DataRowVersion.Original)
    End If
    Console.WriteLine("{0}: {1}, {2} ({3})", i, current, original, rowState)
  Next
End Sub

Private Function GetChangedCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))
  table.Columns.Add("Name", GetType(String))

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

  table.Rows.Add(New Object() {0, "XXX"})
  table.Rows.Add(New Object() {1, "XXX"})
  table.Rows.Add(New Object() {2, "XXX"})
  table.Rows.Add(New Object() {3, "XXX"})
  table.Rows.Add(New Object() {4, "XXX"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))
  table.Columns.Add("Name", GetType(String))

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

  table.Rows.Add(New Object() {0, "Mary"})
  table.Rows.Add(New Object() {1, "Andy"})
  table.Rows.Add(New Object() {2, "Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetIntegerTable() As DataTable
  ' Create sample table with a single Int32 column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))

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

  table.Rows.Add(New Object() {4})
  table.Rows.Add(New Object() {5})
  table.AcceptChanges()
  Return table
End Function

Private Function GetStringTable() As DataTable
  ' Create sample table with a single String column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(String))

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

  table.Rows.Add(New Object() {"Mary"})
  table.Rows.Add(New Object() {"Andy"})
  table.Rows.Add(New Object() {"Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Sub PerformDemo(ByVal optionForLoad As LoadOption)

  ' Load data into a DataTable, retrieve a DataTableReader containing
  ' different data, and call the Load method. Depending on the
  ' LoadOption value passed as a parameter, this procedure displays
  ' different results in the DataTable.
  Console.WriteLine(" ============================= ")
  Console.WriteLine("table.Load(reader, {0})", optionForLoad)
  Console.WriteLine(" ============================= ")

  Dim table As DataTable = SetupModifiedRows()
  Dim reader As New DataTableReader(GetChangedCustomers())
  AddHandler table.RowChanging, New _
      DataRowChangeEventHandler(AddressOf HandleRowChanging)

  table.Load(reader, optionForLoad)
  Console.WriteLine()
  DisplayRowState(table)
End Sub

Private Sub PrintColumns( _
   ByVal table As DataTable)

  ' Loop through all the rows in the DataTableReader.
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(row(col).ToString() & " ")
    Next
    Console.WriteLine()
  Next
End Sub

Private Function SetupModifiedRows() As DataTable
  ' Fill a DataTable with customer info, and 
  ' then modify, delete, and add rows.

  Dim table As DataTable = GetCustomers()
  ' Row 0 is unmodified.
  ' Row 1 is modified.
  ' Row 2 is deleted.
  ' Row 3 is added.
  table.Rows(1)("Name") = "Sydney"
  table.Rows(2).Delete()
  Dim row As DataRow = table.NewRow
  row("ID") = 3
  row("Name") = "Melony"
  table.Rows.Add(row)

  ' Note that the code doesn't call
  ' table.AcceptChanges()
  Return table
End Function

Private Sub HandleRowChanging(ByVal sender As Object, _
  ByVal e As System.Data.DataRowChangeEventArgs)
  Console.WriteLine( _
      "RowChanging event: ID = {0}, action = {1}", e.Row("ID"), _
      e.Action)
End Sub

備註

Load 方法可用於多種常見情境,皆圍繞從指定資料來源取得資料並將其加入目前的資料容器(此例 DataTable為 )。 這些情境描述了 的 DataTable標準使用,描述其更新與合併行為。

A DataTable 與單一主要資料來源同步或更新。 DataTable軌跡會改變,使得與主要資料來源同步。 此外,A DataTable 也能接受來自一個或多個次級資料來源的增量資料。 他們 DataTable 不負責追蹤變更以允許與次級資料來源同步。

根據這兩個假設的資料來源,使用者很可能需要以下其中一種行為:

  • 從主要資料來源初始化 DataTable 。 在此情境中,使用者希望以主要資料來源的值初始化一個空 DataTable 位。 之後使用者打算將變更傳回主要資料來源。

  • 保留變更並重新同步於主要資料來源。 在此情境中,使用者希望將 DataTable 前一個情境中已填入的資料,並與主要資料來源進行增量同步,保留在 DataTable.

  • 來自次級資料來源的增量資料流。 在此情境中,使用者希望將一個或多個次要資料來源的變更合併,並將這些變更傳回主要資料來源。

這個 Load 方法讓所有這些情境都成為可能。 除了其中一個外,這個方法的超載都允許你指定載入選項參數,指示已在 DataTable 合併中與列的列如何被載入。 (不允許你指定行為的超載會使用預設的載入選項。)下表說明列舉所 LoadOption 提供的三種載荷選項。 在每種情況下,描述都顯示當資料列的主鍵與現有列的主鍵相符時的行為。

裝載選項 說明
PreserveChanges (預設值) 更新該列的原始版本,並更新該列的值。
OverwriteChanges 更新該列目前及原始版本的下一列值。
Upsert 更新該列的當前版本,並輸入該列的值。

一般而言, PreserveChangesOverwriteChanges 選項是針對使用者需要與 DataSet 主要資料來源同步其變更的情況。 此 Upsert 選項有助於彙整來自一個或多個次級資料來源的變更。

Load(IDataReader)

來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs

利用提供的 IDataReader資料來源 來填入 aDataTable。 如果已經 DataTable 包含資料列,來自資料來源的輸入資料會與現有的資料列合併。

public:
 void Load(System::Data::IDataReader ^ reader);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Members from types used in the expression column to be trimmed if not referenced directly.")]
public void Load(System.Data.IDataReader reader);
public void Load(System.Data.IDataReader reader);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Members from types used in the expression column to be trimmed if not referenced directly.")>]
member this.Load : System.Data.IDataReader -> unit
member this.Load : System.Data.IDataReader -> unit
Public Sub Load (reader As IDataReader)

參數

reader
IDataReader

一個 IDataReader 提供結果集合的

屬性

範例

以下範例展示了呼叫該 Load 方法時涉及的幾個問題。 首先,範例聚焦於結構問題,包括從已載 IDataReader入的結構推斷結構,接著處理不相容的結構,以及缺少或新增欄位的結構。 範例接著呼叫該 Load 方法,並在載入操作前後顯示資料。

static void Main()
{
    // This example examines a number of scenarios involving the
    // DataTable.Load method.
    Console.WriteLine("Load a DataTable and infer its schema:");

    // The table has no schema. The Load method will infer the
    // schema from the IDataReader:
    DataTable table = new DataTable();

    // Retrieve a data reader, based on the Customers data. In
    // an application, this data might be coming from a middle-tier
    // business object:
    DataTableReader reader = new DataTableReader(GetCustomers());

    table.Load(reader);
    PrintColumns(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable from an incompatible IDataReader:");

    // Create a table with a single integer column. Attempt
    // to load data from a reader with a schema that is
    // incompatible. Note the exception, determined
    // by the particular incompatibility:
    table = GetIntegerTable();
    reader = new DataTableReader(GetStringTable());
    try
    {
        table.Load(reader);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
    }

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable with an IDataReader that has extra columns:");

    // Note that loading a reader with extra columns adds
    // the columns to the existing table, if possible:
    table = GetIntegerTable();
    reader = new DataTableReader(GetCustomers());
    table.Load(reader);
    PrintColumns(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable with an IDataReader that has missing columns:");

    // Note that loading a reader with missing columns causes
    // the columns to be filled with null data, if possible:
    table = GetCustomers();
    reader = new DataTableReader(GetIntegerTable());
    table.Load(reader);
    PrintColumns(table);

    // Demonstrate the various possibilites when loading data
    // into a DataTable that already contains data.
    Console.WriteLine(" ============================= ");
    Console.WriteLine("Demonstrate data considerations:");
    Console.WriteLine("Current value, Original value, (RowState)");
    Console.WriteLine(" ============================= ");
    Console.WriteLine("Original table:");

    table = SetupModifiedRows();
    DisplayRowState(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine("Data in IDataReader to be loaded:");
    DisplayRowState(GetChangedCustomers());

    // Load data into a DataTable, retrieve a DataTableReader
    // containing different data, and call the Load method.
    Console.WriteLine(" ============================= ");
    Console.WriteLine("table.Load(reader)");
    Console.WriteLine(" ============================= ");

    table = SetupModifiedRows();
    reader = new DataTableReader(GetChangedCustomers());
    table.Load(reader);
    DisplayRowState(table);

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static void DisplayRowState(DataTable table)
{
    for (int i = 0; i <= table.Rows.Count - 1; i++)
    {
        object current = "--";
        object original = "--";
        DataRowState rowState = table.Rows[i].RowState;

        // Attempt to retrieve the current value, which doesn't exist
        // for deleted rows:
        if (rowState != DataRowState.Deleted)
        {
            current = table.Rows[i]["Name", DataRowVersion.Current];
        }

        // Attempt to retrieve the original value, which doesn't exist
        // for added rows:
        if (rowState != DataRowState.Added)
        {
            original = table.Rows[i]["Name", DataRowVersion.Original];
        }
        Console.WriteLine("{0}: {1}, {2} ({3})", i,
            current, original, rowState);
    }
}

private static DataTable GetChangedCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID",
        typeof(int));
    table.Columns.Add("Name", typeof(string));

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

    table.Rows.Add(new object[] { 1, "XXX" });
    table.Rows.Add(new object[] { 2, "XXX" });
    table.Rows.Add(new object[] { 3, "XXX" });
    table.Rows.Add(new object[] { 4, "XXX" });
    table.Rows.Add(new object[] { 5, "XXX" });
    table.Rows.Add(new object[] { 6, "XXX" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetCustomers()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID",
        typeof(int));
    table.Columns.Add("Name", typeof(string));

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

    table.Rows.Add(new object[] { 1, "Mary" });
    table.Rows.Add(new object[] { 2, "Andy" });
    table.Rows.Add(new object[] { 3, "Peter" });
    table.Rows.Add(new object[] { 4, "Russ" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetIntegerTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID",
        typeof(int));

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

    table.Rows.Add(new object[] { 5 });
    table.Rows.Add(new object[] { 6 });
    table.Rows.Add(new object[] { 7 });
    table.Rows.Add(new object[] { 8 });
    table.AcceptChanges();
    return table;
}

private static DataTable GetStringTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID",
        typeof(string));

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

    table.Rows.Add(new object[] { "Mary" });
    table.Rows.Add(new object[] { "Andy" });
    table.Rows.Add(new object[] { "Peter" });
    table.Rows.Add(new object[] { "Russ" });
    table.AcceptChanges();
    return table;
}

private static void PrintColumns(DataTable table)
{
    // Loop through all the rows in the DataTableReader
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i] + " ");
        }
        Console.WriteLine();
    }
}

private static DataTable SetupModifiedRows()
{
    // Fill a DataTable with customer info, and
    // then modify, delete, and add rows.

    DataTable table = GetCustomers();
    // Row 0 is unmodified.
    // Row 1 is modified.
    // Row 2 is deleted.
    // Row 5 is added.
    table.Rows[1]["Name"] = "Sydney";
    table.Rows[2].Delete();
    DataRow row = table.NewRow();
    row["ID"] = 5;
    row["Name"] = "Melony";
    table.Rows.Add(row);

    // Note that the code doesn't call
    // table.AcceptChanges()
    return table;
}
Sub Main()
  ' This example examines a number of scenarios involving the 
  ' DataTable.Load method.
  Console.WriteLine("Load a DataTable and infer its schema:")

  ' The table has no schema. The Load method will infer the 
  ' schema from the IDataReader:
  Dim table As New DataTable()

  ' Retrieve a data reader, based on the Customers data. In
  ' an application, this data might be coming from a middle-tier
  ' business object:
  Dim reader As New DataTableReader(GetCustomers())

  table.Load(reader)
  PrintColumns(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable from an incompatible IDataReader:")

  ' Create a table with a single integer column. Attempt
  ' to load data from a reader with a schema that is 
  ' incompatible. Note the exception, determined
  ' by the particular incompatibility:
  table = GetIntegerTable()
  reader = New DataTableReader(GetStringTable())
  Try
    table.Load(reader)
  Catch ex As Exception
    Console.WriteLine(ex.GetType.Name & ":" & ex.Message())
  End Try

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable with an IDataReader that has extra columns:")

  ' Note that loading a reader with extra columns adds
  ' the columns to the existing table, if possible:
  table = GetIntegerTable()
  reader = New DataTableReader(GetCustomers())
  table.Load(reader)
  PrintColumns(table)

  Console.WriteLine(" ============================= ")
      Console.WriteLine( _
          "Load a DataTable with an IDataReader that has missing columns:")

  ' Note that loading a reader with missing columns causes 
  ' the columns to be filled with null data, if possible:
  table = GetCustomers()
  reader = New DataTableReader(GetIntegerTable())
  table.Load(reader)
  PrintColumns(table)

  ' Demonstrate the various possibilites when loading data into
  ' a DataTable that already contains data.
  Console.WriteLine(" ============================= ")
  Console.WriteLine("Demonstrate data considerations:")
  Console.WriteLine("Current value, Original value, (RowState)")
  Console.WriteLine(" ============================= ")
  Console.WriteLine("Original table:")

  table = SetupModifiedRows()
  DisplayRowState(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine("Data in IDataReader to be loaded:")
  DisplayRowState(GetChangedCustomers())

  ' Load data into a DataTable, retrieve a DataTableReader 
  ' containing different data, and call the Load method. 
  Console.WriteLine(" ============================= ")
  Console.WriteLine("table.Load(reader)")
  Console.WriteLine(" ============================= ")

  table = SetupModifiedRows()
  reader = New DataTableReader(GetChangedCustomers())
  table.Load(reader)
  DisplayRowState(table)

  Console.WriteLine("Press any key to continue.")
  Console.ReadKey()
End Sub

Private Sub DisplayRowState(ByVal table As DataTable)
  For i As Integer = 0 To table.Rows.Count - 1
    Dim current As Object = "--"
    Dim original As Object = "--"
    Dim rowState As DataRowState = table.Rows(i).RowState

    ' Attempt to retrieve the current value, which doesn't exist
    ' for deleted rows:
    If rowState <> DataRowState.Deleted Then
      current = table.Rows(i)("Name", DataRowVersion.Current)
    End If

    ' Attempt to retrieve the original value, which doesn't exist
    ' for added rows:
    If rowState <> DataRowState.Added Then
      original = table.Rows(i)("Name", DataRowVersion.Original)
    End If
    Console.WriteLine("{0}: {1}, {2} ({3})", i, _
      current, original, rowState)
  Next
End Sub

Private Function GetChangedCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))
  table.Columns.Add("Name", GetType(String))

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

  table.Rows.Add(New Object() {1, "XXX"})
  table.Rows.Add(New Object() {2, "XXX"})
  table.Rows.Add(New Object() {3, "XXX"})
  table.Rows.Add(New Object() {4, "XXX"})
  table.Rows.Add(New Object() {5, "XXX"})
  table.Rows.Add(New Object() {6, "XXX"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))
  table.Columns.Add("Name", GetType(String))

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

  table.Rows.Add(New Object() {1, "Mary"})
  table.Rows.Add(New Object() {2, "Andy"})
  table.Rows.Add(New Object() {3, "Peter"})
  table.Rows.Add(New Object() {4, "Russ"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetIntegerTable() As DataTable
  ' Create sample table with a single Int32 column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))

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

  table.Rows.Add(New Object() {5})
  table.Rows.Add(New Object() {6})
  table.Rows.Add(New Object() {7})
  table.Rows.Add(New Object() {8})
  table.AcceptChanges()
  Return table
End Function

Private Function GetStringTable() As DataTable
  ' Create sample table with a single String column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(String))

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

  table.Rows.Add(New Object() {"Mary"})
  table.Rows.Add(New Object() {"Andy"})
  table.Rows.Add(New Object() {"Peter"})
  table.Rows.Add(New Object() {"Russ"})
  table.AcceptChanges()
  Return table
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

  ' Loop through all the rows in the DataTableReader.
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(row(col).ToString() & " ")
    Next
    Console.WriteLine()
  Next
End Sub

Private Function SetupModifiedRows() As DataTable
  ' Fill a DataTable with customer info, and 
  ' then modify, delete, and add rows.

  Dim table As DataTable = GetCustomers()
  ' Row 0 is unmodified.
  ' Row 1 is modified.
  ' Row 2 is deleted.
  ' Row 5 is added.
  table.Rows(1)("Name") = "Sydney"
  table.Rows(2).Delete()
  Dim row As DataRow = table.NewRow
  row("ID") = 5
  row("Name") = "Melony"
  table.Rows.Add(row)

  ' Note that the code doesn't call
  ' table.AcceptChanges()
  Return table
End Function

備註

Load 方法會從載 IDataReader入的 中取出第一個結果集,並在成功完成後,將讀取器的位置設定為下一個結果集(若有的話)。 在轉換資料時,該 Load 方法使用與該 DbDataAdapter.Fill 方法相同的轉換規則。

Load此方法在載入實例資料IDataReader時必須考慮三個特定問題:結構、資料與事件操作。 在使用該結構時, Load 方法可能會遇到如下表所述的條件。 結構操作適用於所有匯入的結果集,即使沒有資料也一樣。

狀況 行為
DataTable 沒有架構。 Load 方法根據從匯入的 IDataReader結果集推論出該結構。
DataTable 有 schema,但與已載入的 schema 不相容。 Load 方法會拋出一個例外,對應於嘗試將資料載入不相容結構時所發生的特定錯誤。
這些結構是相容的,但載入的結果集結構包含不存在於 DataTable的欄位。 Load 方法將額外的欄位加入 DataTable的結構中。 若 與 DataTable 載入結果集對應欄位不相容,該方法會拋出例外。 該方法同時從結果集中取得所有新增欄位的限制資訊。 除了主鍵限制外,此限制資訊僅在載 DataTable 入操作開始時電流中沒有任何欄位時使用。
這些結構是相容的,但載入的結果集結構包含的欄位數少於 DataTable 若缺失欄位有預設值或資料型別為 null, Load 該方法允許新增列,並以預設 null 值取代缺失欄位。 若無法使用預設值 或 null ,則 Load 該方法會拋出例外。 若未提供特定預設值, Load 該方法將該值作為 null 隱含的預設值。

在考慮方法在資料操作上的行為 Load 之前,請考慮 a DataTable 中的每一列同時維持每欄的當前值與原始值。 這些值可能是等價的,也可能不同,若資料自填入 DataTable。 更多資訊請參閱 列狀態與列版本

此版本 Load 嘗試保留每列的當前值,保留原始值。 (如果你想更細緻地控制輸入資料的行為,請參見 DataTable.Load。)如果現有的列和進入的列包含對應的主鍵值,該列會使用目前的列狀態值處理,否則會被視為新一列。

在事件操作方面, RowChanging 事件發生在每列變更之前,事件 RowChanged 則在每列變更後發生。 在每種情況下, Action 傳遞給事件處理器的實例屬性 DataRowChangeEventArgs 都包含與該事件相關的特定動作資訊。 此動作值取決於載入操作前該列的狀態。 在每個案例中,兩個事件都同時發生,且作用方式相同。 該動作可套用於每列的當前或原始版本,或兩者皆適用,視當前列狀態而定。

下表顯示該 Load 方法的行為。 最後一列(標示為「(不存在)」)描述了與任何現有列不匹配的輸入列的行為。 此表中的每個儲存格描述同一列欄位的當前及原始值,以及 DataRowState 方法完成後 Load 的值。 在這種情況下,該方法不允許你指定載入選項,而是使用預設 PreserveChanges的 。

現有 DataRowState 方法與事件動作之後 Load 的值
已新增 Current = <現有>

原始 = <即將抵達>

狀態 = <修改版>

RowAction = ChangeOriginal
已修改 Current = <現有>

原始 = <即將抵達>

狀態 = <修改版>

RowAction = ChangeOriginal
已刪除 目前 = <不可用>

原始 = <即將抵達>

狀態 = <已刪除>

RowAction = ChangeOriginal
未更改 Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
(未出席) Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal

A 中的 DataColumn 值可以透過使用如 ReadOnlyAutoIncrement等性質來約束。 該 Load 方法以符合欄位屬性定義行為的方式處理此類欄位。 a DataColumn 的唯讀限制僅適用於記憶體中發生的變更。 Load該方法會覆寫只讀欄位的值(如有需要)。

為了決定要用哪個版本的主鍵欄位來比較目前列與輸入列,方法會 Load 使用該列內原始的主鍵值(如果存在的話)。 否則,該 Load 方法使用當前版本的主鍵欄位。

另請參閱

適用於

Load(IDataReader, LoadOption)

來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs

利用提供的 IDataReader資料來源 來填入 aDataTable。 若已 DataTable 包含列數,則根據參數值 loadOption ,資料來源的輸入資料會與現有資料列合併。

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Using LoadOption may cause members from types used in the expression column to be trimmed if not referenced directly.")]
public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption);
public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Using LoadOption may cause members from types used in the expression column to be trimmed if not referenced directly.")>]
member this.Load : System.Data.IDataReader * System.Data.LoadOption -> unit
member this.Load : System.Data.IDataReader * System.Data.LoadOption -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption)

參數

reader
IDataReader

一個 IDataReader 提供一個或多個結果集的 。

loadOption
LoadOption

列舉中的一個值 LoadOption ,表示已在 中的 DataTable 列與共用相同主鍵的入列如何結合。

屬性

範例

以下範例展示了呼叫該 Load 方法時涉及的幾個問題。 首先,範例聚焦於結構問題,包括從已載 IDataReader入的結構推斷結構,接著處理不相容的結構,以及缺少或新增欄位的結構。 接著範例聚焦於資料議題,包括處理各種載入選項。

static void Main()
{
    // This example examines a number of scenarios involving the
    // DataTable.Load method.
    Console.WriteLine("Load a DataTable and infer its schema:");

    // The table has no schema. The Load method will infer the
    // schema from the IDataReader:
    DataTable table = new DataTable();

    // Retrieve a data reader, based on the Customers data. In
    // an application, this data might be coming from a middle-tier
    // business object:
    DataTableReader reader = new DataTableReader(GetCustomers());

    table.Load(reader);
    PrintColumns(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable from an incompatible IDataReader:");

    // Create a table with a single integer column. Attempt
    // to load data from a reader with a schema that is
    // incompatible. Note the exception, determined
    // by the particular incompatibility:
    table = GetIntegerTable();
    reader = new DataTableReader(GetStringTable());
    try
    {
        table.Load(reader);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
    }

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable with an IDataReader that has extra columns:");

    // Note that loading a reader with extra columns adds
    // the columns to the existing table, if possible:
    table = GetIntegerTable();
    reader = new DataTableReader(GetCustomers());
    table.Load(reader);
    PrintColumns(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine(
        "Load a DataTable with an IDataReader that has missing columns:");

    // Note that loading a reader with missing columns causes
    // the columns to be filled with null data, if possible:
    table = GetCustomers();
    reader = new DataTableReader(GetIntegerTable());
    table.Load(reader);
    PrintColumns(table);

    // Demonstrate the various possibilites when loading data into
    // a DataTable that already contains data.
    Console.WriteLine(" ============================= ");
    Console.WriteLine("Demonstrate data considerations:");
    Console.WriteLine("Current value, Original value, (RowState)");
    Console.WriteLine(" ============================= ");
    Console.WriteLine("Original table:");

    table = SetupModifiedRows();
    DisplayRowState(table);

    Console.WriteLine(" ============================= ");
    Console.WriteLine("Data in IDataReader to be loaded:");
    DisplayRowState(GetChangedCustomers());

    PerformDemo(LoadOption.OverwriteChanges);
    PerformDemo(LoadOption.PreserveChanges);
    PerformDemo(LoadOption.Upsert);

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static void DisplayRowState(DataTable table)
{
    for (int i = 0; i <= table.Rows.Count - 1; i++)
    {
        object current = "--";
        object original = "--";
        DataRowState rowState = table.Rows[i].RowState;

        // Attempt to retrieve the current value, which doesn't exist
        // for deleted rows:
        if (rowState != DataRowState.Deleted)
        {
            current = table.Rows[i]["Name", DataRowVersion.Current];
        }

        // Attempt to retrieve the original value, which doesn't exist
        // for added rows:
        if (rowState != DataRowState.Added)
        {
            original = table.Rows[i]["Name", DataRowVersion.Original];
        }
        Console.WriteLine("{0}: {1}, {2} ({3})", i,
            current, original, rowState);
    }
}

private static DataTable GetChangedCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

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

    table.Rows.Add(new object[] { 0, "XXX" });
    table.Rows.Add(new object[] { 1, "XXX" });
    table.Rows.Add(new object[] { 2, "XXX" });
    table.Rows.Add(new object[] { 3, "XXX" });
    table.Rows.Add(new object[] { 4, "XXX" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetCustomers()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));

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

    table.Rows.Add(new object[] { 0, "Mary" });
    table.Rows.Add(new object[] { 1, "Andy" });
    table.Rows.Add(new object[] { 2, "Peter" });
    table.AcceptChanges();
    return table;
}

private static DataTable GetIntegerTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));

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

    table.Rows.Add(new object[] { 4 });
    table.Rows.Add(new object[] { 5 });
    table.AcceptChanges();
    return table;
}

private static DataTable GetStringTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(string));

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

    table.Rows.Add(new object[] { "Mary" });
    table.Rows.Add(new object[] { "Andy" });
    table.Rows.Add(new object[] { "Peter" });
    table.AcceptChanges();
    return table;
}

private static void PerformDemo(LoadOption optionForLoad)
{

    // Load data into a DataTable, retrieve a DataTableReader containing
    // different data, and call the Load method. Depending on the
    // LoadOption value passed as a parameter, this procedure displays
    // different results in the DataTable.
    Console.WriteLine(" ============================= ");
    Console.WriteLine("table.Load(reader, {0})", optionForLoad);
    Console.WriteLine(" ============================= ");

    DataTable table = SetupModifiedRows();
    DataTableReader reader = new DataTableReader(GetChangedCustomers());
    table.RowChanging +=new DataRowChangeEventHandler(HandleRowChanging);

    table.Load(reader, optionForLoad);
    Console.WriteLine();
    DisplayRowState(table);
}

private static void PrintColumns(DataTable table)
{
    // Loop through all the rows in the DataTableReader
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i] + " ");
        }
        Console.WriteLine();
    }
}

private static DataTable SetupModifiedRows()
{
    // Fill a DataTable with customer info, and
    // then modify, delete, and add rows.

    DataTable table = GetCustomers();
    // Row 0 is unmodified.
    // Row 1 is modified.
    // Row 2 is deleted.
    // Row 3 is added.
    table.Rows[1]["Name"] = "Sydney";
    table.Rows[2].Delete();
    DataRow row = table.NewRow();
    row["ID"] = 3;
    row["Name"] = "Melony";
    table.Rows.Add(row);

    // Note that the code doesn't call
    // table.AcceptChanges()
    return table;
}

static void HandleRowChanging(object sender, DataRowChangeEventArgs e)
{
    Console.WriteLine(
        "RowChanging event: ID = {0}, action = {1}", e.Row["ID"], e.Action);
}
Sub Main()
  Dim table As New DataTable()

  ' This example examines a number of scenarios involving the
  '  DataTable.Load method.
  Console.WriteLine("Load a DataTable and infer its schema:")

  ' Retrieve a data reader, based on the Customers data. In
  ' an application, this data might be coming from a middle-tier
  ' business object:
  Dim reader As New DataTableReader(GetCustomers())

  ' The table has no schema. The Load method will infer the 
  ' schema from the IDataReader:
  table.Load(reader)
  PrintColumns(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable from an incompatible IDataReader:")

  ' Create a table with a single integer column. Attempt
  ' to load data from a reader with a schema that is 
  ' incompatible. Note the exception, determined
  ' by the particular incompatibility:
  table = GetIntegerTable()
  reader = New DataTableReader(GetStringTable())
  Try
    table.Load(reader)
  Catch ex As Exception
    Console.WriteLine(ex.GetType.Name & ":" & ex.Message())
  End Try

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable with an IDataReader that has extra columns:")

  ' Note that loading a reader with extra columns adds
  ' the columns to the existing table, if possible:
  table = GetIntegerTable()
  reader = New DataTableReader(GetCustomers())
  table.Load(reader)
  PrintColumns(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine( _
      "Load a DataTable with an IDataReader that has missing columns:")

  ' Note that loading a reader with missing columns causes 
  ' the columns to be filled with null data, if possible:
  table = GetCustomers()
  reader = New DataTableReader(GetIntegerTable())
  table.Load(reader)
  PrintColumns(table)

  ' Demonstrate the various possibilites when loading data into
  ' a DataTable that already contains data.
  Console.WriteLine(" ============================= ")
  Console.WriteLine("Demonstrate data considerations:")
  Console.WriteLine("Current value, Original value, (RowState)")
  Console.WriteLine(" ============================= ")
  Console.WriteLine("Original table:")

  table = SetupModifiedRows()
  DisplayRowState(table)

  Console.WriteLine(" ============================= ")
  Console.WriteLine("Data in IDataReader to be loaded:")
  DisplayRowState(GetChangedCustomers())

  PerformDemo(LoadOption.OverwriteChanges)
  PerformDemo(LoadOption.PreserveChanges)
  PerformDemo(LoadOption.Upsert)

  Console.WriteLine("Press any key to continue.")
  Console.ReadKey()
End Sub

Private Sub DisplayRowState(ByVal table As DataTable)
  For i As Integer = 0 To table.Rows.Count - 1
    Dim current As Object = "--"
    Dim original As Object = "--"
    Dim rowState As DataRowState = table.Rows(i).RowState

    ' Attempt to retrieve the current value, which doesn't exist
    ' for deleted rows:
    If rowState <> DataRowState.Deleted Then
      current = table.Rows(i)("Name", DataRowVersion.Current)
    End If

    ' Attempt to retrieve the original value, which doesn't exist
    ' for added rows:
    If rowState <> DataRowState.Added Then
      original = table.Rows(i)("Name", DataRowVersion.Original)
    End If
    Console.WriteLine("{0}: {1}, {2} ({3})", i, _
      current, original, rowState)
  Next
End Sub

Private Function GetChangedCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))
  table.Columns.Add("Name", GetType(String))

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

  table.Rows.Add(New Object() {0, "XXX"})
  table.Rows.Add(New Object() {1, "XXX"})
  table.Rows.Add(New Object() {2, "XXX"})
  table.Rows.Add(New Object() {3, "XXX"})
  table.Rows.Add(New Object() {4, "XXX"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable

  ' Create two columns, ID and Name.
  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))
  table.Columns.Add("Name", GetType(String))

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

  table.Rows.Add(New Object() {0, "Mary"})
  table.Rows.Add(New Object() {1, "Andy"})
  table.Rows.Add(New Object() {2, "Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Function GetIntegerTable() As DataTable
  ' Create sample table with a single Int32 column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(Integer))

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

  table.Rows.Add(New Object() {4})
  table.Rows.Add(New Object() {5})
  table.AcceptChanges()
  Return table
End Function

Private Function GetStringTable() As DataTable
  ' Create sample table with a single String column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(String))

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

  table.Rows.Add(New Object() {"Mary"})
  table.Rows.Add(New Object() {"Andy"})
  table.Rows.Add(New Object() {"Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Sub PerformDemo(ByVal optionForLoad As LoadOption)

  ' Load data into a DataTable, retrieve a DataTableReader containing
  ' different data, and call the Load method. Depending on the
  ' LoadOption value passed as a parameter, this procedure displays
  ' different results in the DataTable.
  Console.WriteLine(" ============================= ")
  Console.WriteLine("table.Load(reader, {0})", optionForLoad)
  Console.WriteLine(" ============================= ")

  Dim table As DataTable = SetupModifiedRows()
  Dim reader As New DataTableReader(GetChangedCustomers())
  AddHandler table.RowChanging, New _
      DataRowChangeEventHandler(AddressOf HandleRowChanging)

  table.Load(reader, optionForLoad)
  Console.WriteLine()
  DisplayRowState(table)
End Sub

Private Sub PrintColumns( _
   ByVal table As DataTable)

  ' Loop through all the rows in the DataTableReader.
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(row(col).ToString() & " ")
    Next
    Console.WriteLine()
  Next
End Sub

Private Function SetupModifiedRows() As DataTable
  ' Fill a DataTable with customer info, and 
  ' then modify, delete, and add rows.

  Dim table As DataTable = GetCustomers()
  ' Row 0 is unmodified.
  ' Row 1 is modified.
  ' Row 2 is deleted.
  ' Row 3 is added.
  table.Rows(1)("Name") = "Sydney"
  table.Rows(2).Delete()
  Dim row As DataRow = table.NewRow
  row("ID") = 3
  row("Name") = "Melony"
  table.Rows.Add(row)

  ' Note that the code doesn't call
  ' table.AcceptChanges()
  Return table
End Function

Private Sub HandleRowChanging(ByVal sender As Object, _
      ByVal e As System.Data.DataRowChangeEventArgs)
  Console.WriteLine( _
      "RowChanging event: ID = {0}, action = {1}", e.Row("ID"), e.Action)
End Sub

備註

Load 方法會從載 IDataReader入的 中取出第一個結果集,並在成功完成後,將讀取器的位置設定為下一個結果集(若有的話)。 在轉換資料時,該 Load 方法使用與該 Fill 方法相同的轉換規則。

Load此方法在載入實例資料IDataReader時必須考慮三個特定問題:結構、資料與事件操作。 在使用該結構時, Load 方法可能會遇到如下表所述的條件。 結構操作適用於所有匯入的結果集,即使沒有資料也一樣。

狀況 行為
DataTable 沒有架構。 Load 方法根據從匯入的 IDataReader結果集推論出該結構。
DataTable 有 schema,但與已載入的 schema 不相容。 Load 方法會拋出一個例外,對應於嘗試將資料載入不相容結構時所發生的特定錯誤。
這些結構是相容的,但載入的結果集結構包含不存在 DataTable於 . Load 方法將額外的欄位加入 DataTable的結構中。 若 與 DataTable 載入結果集對應欄位不相容,該方法會拋出例外。 該方法同時從結果集中取得所有新增欄位的限制資訊。 除了主鍵限制外,此限制資訊僅在載 DataTable 入操作開始時電流中沒有任何欄位時使用。
這些結構是相容的,但載入的結果集結構包含的欄位數少於 DataTable 如果缺失的欄位有預設值或欄位的資料型別是可空的,該 Load 方法允許新增這些列,並以預設值或空值替換缺失欄位。 若無法使用預設值或 null,則 Load 該方法會拋出例外。 若未提供特定預設值, Load 則以空值作為隱含的預設值。

在考慮方法在資料操作上的行為 Load 之前,請考慮 a DataTable 中的每一列同時維持每欄的當前值與原始值。 這些值可能是等價的,也可能不同,若資料自填入 DataTable。 更多資訊請參閱 列狀態與列版本

在此方法呼叫中,指定的 LoadOption 參數會影響輸入資料的處理。 Load 方法應該如何處理與現有列主鍵相同的載入列? 它應該修改目前的數值、原始數值,還是兩者都修改? 這些問題以及更多,都由參數 loadOption 控制。

如果現有的列和進入的列包含對應的主鍵值,該列會使用目前的列狀態值處理,否則會被視為新一列。

在事件操作方面, RowChanging 事件發生在每列變更之前,事件 RowChanged 則在每列變更後發生。 在每種情況下, Action 傳遞給事件處理器的實例屬性 DataRowChangeEventArgs 都包含與該事件相關的特定動作資訊。 此動作值會依載入前該列的狀態而有所不同。 在每個案例中,兩個事件都同時發生,且作用方式相同。 該動作可套用於每列的當前或原始版本,或兩者皆適用,視當前列狀態而定。

下表顯示 Load 方法在每個值時 LoadOption 的行為,並展示這些值如何與被載入列的列狀態互動。 最後一列(標示為「(不存在)」)描述了與任何現有列不匹配的輸入列的行為。 此表中的每個儲存格描述同一列欄位的當前及原始值,以及 DataRowState 方法完成後 Load 的值。

現有 DataRowState Upsert 覆寫變更 保留變更(預設行為)
已新增 Current = <進入>

原始 = -<不可用>

州 = <附加>

RowAction = 變更
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
Current = <現有>

原始 = <即將抵達>

狀態 = <修改版>

RowAction = ChangeOriginal
已修改 Current = <進入>

原始 = <現存>

狀態 = <修改版>

RowAction = 變更
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
Current = <現有>

原始 = <即將抵達>

狀態 = <修改版>

RowAction =ChangeOriginal
已刪除 (載入不會影響已刪除的列)

Current = ---

原始 = <現存>

狀態 = <已刪除>

(新增一列具有以下特徵)

Current = <進入>

原始 = <不可取得>

州 = <附加>

RowAction = 加法
還原刪除,以及

Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
目前 = <不可用>

原始 = <即將抵達>

狀態 = <已刪除>

RowAction = ChangeOriginal
未更改 Current = <進入>

原始 = <現存>

如果新值與現有值相同,則

狀態 = <不變>

RowAction = 無

否則

狀態 = <修改版>

RowAction = 變更
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
不在場) Current = <進入>

原始 = <不可取得>

州 = <附加>

RowAction = 加法
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal

A 中的 DataColumn 值可以透過使用如 ReadOnlyAutoIncrement等性質來約束。 該 Load 方法以符合欄位屬性定義行為的方式處理此類欄位。 a DataColumn 的唯讀限制僅適用於記憶體中發生的變更。 Load該方法會覆寫只讀欄位的值(如有需要)。

如果你在呼叫 Load 方法時指定 OverwriteChanges 或 PreserveChanges 選項,就會假設輸入資料來自 DataTable的主要資料來源,DataTable 會追蹤變更並能將變更傳回資料來源。 若選擇 Upsert 選項,假設資料來自次級資料來源,例如由中階元件提供的資料,且可能被使用者修改。 在此情況下,假設意圖是彙整來自 中一個或多個資料來源 DataTable的資料,然後可能將資料傳播回主要資料來源。 參數 LoadOption 用於決定用於主鍵比較的具體資料列版本。 下表提供了詳細資訊。

裝載選項 用於主鍵比較的 DataRow 版本
OverwriteChanges 如果有原始版本,則為現行版本
PreserveChanges 如果有原始版本,則為現行版本
Upsert 如果有現行版本(若有的話);否則為原始版本

另請參閱

適用於

Load(IDataReader, LoadOption, FillErrorEventHandler)

來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs
來源:
DataTable.cs

利用錯誤處理代理所提供的IDataReader資料,填DataTable入資料來源的值。

public:
 virtual void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, System::Data::FillErrorEventHandler ^ errorHandler);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Using LoadOption may cause members from types used in the expression column to be trimmed if not referenced directly.")]
public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler? errorHandler);
public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler? errorHandler);
public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Using LoadOption may cause members from types used in the expression column to be trimmed if not referenced directly.")>]
abstract member Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
abstract member Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
Public Overridable Sub Load (reader As IDataReader, loadOption As LoadOption, errorHandler As FillErrorEventHandler)

參數

reader
IDataReader

IDataReader A 提供結果集。

loadOption
LoadOption

列舉中的一個值 LoadOption ,表示已在 中的 DataTable 列與共用相同主鍵的入列如何結合。

errorHandler
FillErrorEventHandler

當載入資料時發生錯誤時,會呼叫一個 FillErrorEventHandler 代理。

屬性

範例

static void Main()
{
    // Attempt to load data from a data reader in which
    // the schema is incompatible with the current schema.
    // If you use exception handling, you won't get the chance
    // to examine each row, and each individual table,
    // as the Load method progresses.
    // By taking advantage of the FillErrorEventHandler delegate,
    // you can interact with the Load process as an error occurs,
    // attempting to fix the problem, or simply continuing or quitting
    // the Load process:
    DataTable table = GetIntegerTable();
    DataTableReader reader = new DataTableReader(GetStringTable());
    table.Load(reader, LoadOption.OverwriteChanges, FillErrorHandler);

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static DataTable GetIntegerTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));

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

    table.Rows.Add(new object[] { 4 });
    table.Rows.Add(new object[] { 5 });
    table.AcceptChanges();
    return table;
}

private static DataTable GetStringTable()
{
    // Create sample Customers table, in order
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(string));

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

    table.Rows.Add(new object[] { "Mary" });
    table.Rows.Add(new object[] { "Andy" });
    table.Rows.Add(new object[] { "Peter" });
    table.AcceptChanges();
    return table;
}

static void FillErrorHandler(object sender, FillErrorEventArgs e)
{
    // You can use the e.Errors value to determine exactly what
    // went wrong.
    if (e.Errors.GetType() == typeof(System.FormatException))
    {
        Console.WriteLine("Error when attempting to update the value: {0}",
            e.Values[0]);
    }

    // Setting e.Continue to True tells the Load
    // method to continue trying. Setting it to False
    // indicates that an error has occurred, and the
    // Load method raises the exception that got
    // you here.
    e.Continue = true;
}
Sub Main()
  Dim table As New DataTable()

  ' Attempt to load data from a data reader in which
  ' the schema is incompatible with the current schema.
  ' If you use exception handling, you won't get the chance
  ' to examine each row, and each individual table,
  ' as the Load method progresses.
  ' By taking advantage of the FillErrorEventHandler delegate,
  ' you can interact with the Load process as an error occurs,
  ' attempting to fix the problem, or simply continuing or quitting
  ' the Load process:
  table = GetIntegerTable()
  Dim reader As New DataTableReader(GetStringTable())
  table.Load(reader, LoadOption.OverwriteChanges, _
      AddressOf FillErrorHandler)

  Console.WriteLine("Press any key to continue.")
  Console.ReadKey()
End Sub

Private Sub FillErrorHandler(ByVal sender As Object, _
  ByVal e As FillErrorEventArgs)
  ' You can use the e.Errors value to determine exactly what
  ' went wrong.
  If e.Errors.GetType Is GetType(System.FormatException) Then
    Console.WriteLine("Error when attempting to update the value: {0}", _
      e.Values(0))
  End If

  ' Setting e.Continue to True tells the Load
  ' method to continue trying. Setting it to False
  ' indicates that an error has occurred, and the 
  ' Load method raises the exception that got 
  ' you here.
  e.Continue = True
End Sub

Private Function GetIntegerTable() As DataTable
  ' Create sample table with a single Int32 column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))

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

  table.Rows.Add(New Object() {4})
  table.Rows.Add(New Object() {5})
  table.TableName = "IntegerTable"
  table.AcceptChanges()
  Return table
End Function

Private Function GetStringTable() As DataTable
  ' Create sample table with a single String column.
  Dim table As New DataTable

  Dim idColumn As DataColumn = table.Columns.Add("ID", _
      GetType(String))

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

  table.Rows.Add(New Object() {"Mary"})
  table.Rows.Add(New Object() {"Andy"})
  table.Rows.Add(New Object() {"Peter"})
  table.AcceptChanges()
  Return table
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

  ' Loop through all the rows in the DataTableReader.
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(row(col).ToString() & " ")
    Next
    Console.WriteLine()
  Next
End Sub

備註

Load 方法會從載 IDataReader入的 中取出第一個結果集,並在成功完成後,將讀取器的位置設定為下一個結果集(若有的話)。 在轉換資料時,該 Load 方法使用與該 DbDataAdapter.Fill 方法相同的轉換規則。

Load此方法在載入實例資料IDataReader時必須考慮三個特定問題:結構、資料與事件操作。 在使用該結構時, Load 方法可能會遇到如下表所述的條件。 結構操作適用於所有匯入的結果集,即使沒有資料也一樣。

狀況 行為
DataTable 沒有架構。 Load 方法根據從匯入的 IDataReader結果集推論出該結構。
DataTable 有 schema,但與已載入的 schema 不相容。 Load 方法會拋出一個例外,對應於嘗試將資料載入不相容結構時所發生的特定錯誤。
這些結構是相容的,但載入的結果集結構包含不存在 DataTable於 . Load 方法將額外的欄位加入 DataTable的結構中。 若 與 DataTable 載入結果集對應欄位不相容,該方法會拋出例外。 該方法同時從結果集中取得所有新增欄位的限制資訊。 除了主鍵限制外,此限制資訊僅在載 DataTable 入操作開始時電流中沒有任何欄位時使用。
這些結構是相容的,但載入的結果集結構包含的欄位數少於 DataTable 如果缺失的欄位有預設值或欄位的資料型別是可空的,該 Load 方法允許新增這些列,並以預設值或空值替換缺失欄位。 若無法使用預設值或 null,則 Load 該方法會拋出例外。 若未提供特定預設值, Load 則以空值作為隱含的預設值。

在考慮方法在資料操作上的行為 Load 之前,請考慮 a DataTable 中的每一列同時維持每欄的當前值與原始值。 這些值可能是等價的,也可能不同,若資料自填入 DataTable。 更多資訊請參閱 列狀態與列版本

在此方法呼叫中,指定的 LoadOption 參數會影響輸入資料的處理。 Load 方法應該如何處理與現有列主鍵相同的載入列? 它應該修改目前的數值、原始數值,還是兩者都修改? 這些問題以及更多,都由參數 loadOption 控制。

如果現有的列和進入的列包含對應的主鍵值,該列會使用目前的列狀態值處理,否則會被視為新一列。

在事件操作方面, RowChanging 事件發生在每列變更之前,事件 RowChanged 則在每列變更後發生。 在每種情況下, Action 傳遞給事件處理器的實例屬性 DataRowChangeEventArgs 都包含與該事件相關的特定動作資訊。 此動作值會依載入前該列的狀態而有所不同。 在每個案例中,兩個事件都同時發生,且作用方式相同。 該動作可套用於每列的當前或原始版本,或兩者皆適用,視當前列狀態而定。

下表顯示 Load 方法在每個值時 LoadOption 的行為,並展示這些值如何與被載入列的列狀態互動。 最後一列(標示為「(不存在)」)描述了與任何現有列不匹配的輸入列的行為。 此表中的每個儲存格描述同一列欄位的當前及原始值,以及 DataRowState 方法完成後 Load 的值。

現有 DataRowState Upsert 覆寫變更 保留變更(預設行為)
已新增 Current = <進入>

原始 = -<不可用>

州 = <附加>

RowAction = 變更
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
Current = <現有>

原始 = <即將抵達>

狀態 = <修改版>

RowAction = ChangeOriginal
已修改 Current = <進入>

原始 = <現存>

狀態 = <修改版>

RowAction = 變更
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
Current = <現有>

原始 = <即將抵達>

狀態 = <修改版>

RowAction =ChangeOriginal
被 eleted (載入不會影響已刪除的列)

Current = ---

原始 = <現存>

狀態 = <已刪除>

(新增一列具有以下特徵)

Current = <進入>

原始 = <不可取得>

州 = <附加>

RowAction = 加法
還原刪除,以及

Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
目前 = <不可用>

原始 = <即將抵達>

狀態 = <已刪除>

RowAction = ChangeOriginal
未更改 Current = <進入>

原始 = <現存>

如果新值與現有值相同,則

狀態 = <不變>

RowAction = 無

否則

狀態 = <修改版>

RowAction = 變更
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
不在場) Current = <進入>

原始 = <不可取得>

州 = <附加>

RowAction = 加法
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal
Current = <進入>

原始 = <即將抵達>

狀態 = <不變>

RowAction = ChangeCurrentAndOriginal

A 中的 DataColumn 值可以透過使用如 ReadOnlyAutoIncrement等性質來約束。 該 Load 方法以符合欄位屬性定義行為的方式處理此類欄位。 a DataColumn 的唯讀限制僅適用於記憶體中發生的變更。 Load該方法會覆寫只讀欄位的值(如有需要)。

如果你在呼叫 Load 方法時指定 OverwriteChanges 或 PreserveChanges 選項,就會假設輸入資料來自 DataTable的主要資料來源,DataTable 會追蹤變更並能將變更傳回資料來源。 若選擇 Upsert 選項,假設資料來自次級資料來源,例如由中階元件提供的資料,且可能被使用者修改。 在此情況下,假設意圖是彙整來自 中一個或多個資料來源 DataTable的資料,然後可能將資料傳播回主要資料來源。 參數 LoadOption 用於決定用於主鍵比較的具體資料列版本。 下表提供了詳細資訊。

裝載選項 用於主鍵比較的 DataRow 版本
OverwriteChanges 如果有原始版本,則為現行版本
PreserveChanges 如果有原始版本,則為現行版本
Upsert 如果有現行版本(若有的話);否則為原始版本

參數 errorHandler 是一個 FillErrorEventHandler 代理,指的是載入資料時發生錯誤時所呼叫的程序。 FillErrorEventArgs傳遞給程序的參數提供了屬性,讓你能取得關於發生錯誤、當前資料列以及被填入的資料DataTable資訊。 使用這種代理機制,而非較簡單的嘗試/接球區塊,能讓你判斷錯誤、處理情況,並繼續處理。 參數 FillErrorEventArgs 提供一個 Continue 屬性:將此屬性設為 表示 true 你已處理錯誤並希望繼續處理。 將屬性設為 , false 表示你希望停止處理。 請注意,將屬性設為 會 false 觸發問題的程式碼拋出例外。

另請參閱

適用於