DataTable.Load 方法

定義

使用所提供的 DataTable,用資料來源的值填滿 IDataReader。 如果 DataTable 已經包含資料列,從資料來源傳入的資料會與現有的資料列合併。

多載

Load(IDataReader)

使用所提供的 DataTable,用資料來源的值填滿 IDataReader。 如果 DataTable 已經包含資料列,從資料來源傳入的資料會與現有的資料列合併。

Load(IDataReader, LoadOption)

使用所提供的 DataTable,用資料來源的值填滿 IDataReader。 如果 DataTable 已經包含資料列,從資料來源傳入的資料會根據 loadOption 參數的值,與現有的資料列合併。

Load(IDataReader, LoadOption, FillErrorEventHandler)

使用所提供的 DataTable,以資料來源的值填滿 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());

    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,描述其更新和合併行為。

DataTable 同步處理或更新與單一主要數據源。 追蹤 DataTable 變更,允許與主要數據源同步處理。 此外, DataTable 也可以接受來自一或多個次要數據源的累加數據。 DataTable不負責追蹤變更,以便允許與次要數據源進行同步處理。

假設這兩個假設數據源,使用者可能需要下列其中一個行為:

  • 從主要數據源初始化 DataTable 。 在此案例中,使用者想要使用來自主要資料來源的值初始化空 DataTable 的 。 稍後,使用者想要將變更傳播回主要數據源。

  • 保留變更並從主要數據源重新同步處理。 在此案例中,使用者想要擷 DataTable 取上一個案例中填入的 ,並執行與主要數據源的累加同步處理,並保留 中 DataTable所做的修改。

  • 來自次要數據源的累加數據摘要。 在此案例中,使用者想要合併來自一或多個次要數據源的變更,並將這些變更傳播回主要數據源。

方法 Load 可讓所有這些案例都可行。 這個方法的其中一個多載都可讓您指定載入選項參數,指出數據列 DataTable 如何結合所載入的數據列。 (不允許指定行為的多載會使用預設載入選項。) 下表描述列舉所提供的 LoadOption 三個載入選項。 在每個案例中,描述會指出傳入數據中數據列的主鍵符合現有數據列的主鍵時的行為。

載入選項 描述
PreserveChanges (預設) 匯報 內送數據列值的原始數據列版本。
OverwriteChanges 匯報 具有內送數據列值的目前和原始數據列版本。
Upsert 匯報 具有內送數據列值的目前數據列版本。

一般而言, PreserveChangesOverwriteChanges 選項適用於使用者需要同步 DataSet 處理 和其變更與主要數據源的案例。 此選項 Upsert 有助於匯總來自一或多個次要數據源的變更。

Load(IDataReader)

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

使用所提供的 DataTable,用資料來源的值填滿 IDataReader。 如果 DataTable 已經包含資料列,從資料來源傳入的資料會與現有的資料列合併。

public:
 void Load(System::Data::IDataReader ^ reader);
public void Load (System.Data.IDataReader reader);
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具有架構,但與載入的架構不相容。 方法 Load 會擲回對應於嘗試將數據載入不相容架構時所發生之特定錯誤的例外狀況。
架構相容,但載入的結果集架構包含中 DataTable不存在的數據行。 方法 Load 會將額外的數據行新增至 DataTable的架構。 如果和載入的結果集中的對應 DataTable 數據行不相容,方法就會擲回例外狀況。 方法也會從所有新增數據行的結果集中擷取條件約束資訊。 除了主鍵條件約束的情況之外,只有在目前 DataTable 未在載入作業開始時包含任何數據行時,才會使用此條件約束資訊。
架構相容,但載入的結果集架構包含的數據行數目比的 DataTable少。 如果遺漏的數據行已定義預設值,或數據行的數據類型為可為 Null, Load 則此方法可允許加入數據列,並取代遺漏數據行的預設值或 null 值。 如果沒有預設值或 null 可以使用,則 Load 方法會擲回例外狀況。 如果未提供特定的預設值,方法會 Load 使用 null 值做為隱含的預設值。

在考慮方法在數據作業方面的行為 Load 之前,請考慮 中的每個數據列 DataTable 都會維護每個數據行的目前值和原始值。 這些值可能相等,或者,如果數據列中的數據在填滿 DataTable之後已變更,則這些值可能不同。 如需詳細資訊,請參閱 數據列狀態和數據列版本

這個版本的 Load 方法會嘗試保留每個數據列中目前的值,讓原始值保持不變。 (如果您想要更精細地控制傳入數據的行為,請參閱 DataTable.Load.) 如果現有的數據列和傳入數據列包含對應的主鍵值,則會使用目前的數據列狀態值來處理數據列,否則它會被視為新數據列。

就事件作業而言,事件 RowChanging 會在變更每個數據列之前發生,而且事件 RowChanged 會在變更每個數據列之後發生。 在每個案例中 Action ,傳遞至事件處理程式之 DataRowChangeEventArgs 實例的 屬性都包含與事件相關聯的特定動作相關信息。 此動作值取決於載入作業之前的數據列狀態。 在每個案例中,都會發生這兩個事件,而且每個事件的動作都相同。 動作可能會套用至每個數據列的目前或原始版本,或兩者,視目前的數據列狀態而定。

下表顯示 方法的行為 Load 。 標示為「 (不存在) 」的最後一個數據列 () 描述不符合任何現有數據列的傳入數據列行為。 此表格中的每個儲存格都會描述數據列內欄位的目前和原始值,以及在 DataRowState 方法完成之後 Load 的值。 在這裡情況下,方法不允許您指出載入選項,並使用預設值 PreserveChanges

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

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
修改日期 目前 = <現有>

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
已刪除 目前 = <無法使用>

Original = <Incoming>

State = <Deleted>

RowAction = ChangeOriginal
未變更 目前 = <傳入>

Original = <Incoming>

State = <未變更>

RowAction = ChangeCurrentAndOriginal
(不存在) 目前 = <傳入>

Original = <Incoming>

State = <未變更>

RowAction = ChangeCurrentAndOriginal

中的DataColumn值可以使用 和 AutoIncrementReadOnly屬性來限制。 方法會 Load 以與數據行屬性所定義的行為一致的方式來處理這類數據行。 上的 DataColumn 只讀條件約束僅適用於記憶體中發生的變更。 Load方法會視需要覆寫唯讀數據行值。

若要判斷要用來比較目前數據列與傳入數據列的主鍵欄位版本,如果數據列存在,此方法 Load 會使用數據列內主鍵值的原始版本。 否則, Load 方法會使用目前版本的主鍵欄位。

另請參閱

適用於

Load(IDataReader, LoadOption)

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

使用所提供的 DataTable,用資料來源的值填滿 IDataReader。 如果 DataTable 已經包含資料列,從資料來源傳入的資料會根據 loadOption 參數的值,與現有的資料列合併。

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption);
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具有架構,但與載入的架構不相容。 方法 Load 會擲回與嘗試將數據載入不相容架構時所發生之特定錯誤的例外狀況。
架構相容,但載入的結果集架構包含 中不存在 DataTable的數據行。 方法 Load 會將額外的數據行新增至 DataTable的架構。 如果 中 DataTable 對應的數據行和載入的結果集與值不相容,方法會擲回例外狀況。 方法也會從所有新增數據行的結果集中擷取條件約束資訊。 除了主鍵條件約束的情況之外,只有在目前 DataTable 未在載入作業開始時包含任何數據行時,才會使用此條件約束資訊。
架構相容,但載入的結果集架構包含的數據行少於 DataTable 如果遺漏的數據行具有已定義的預設值,或數據行的數據類型可為 Null, Load 則方法允許加入數據列,並取代遺漏數據行的預設或 Null 值。 如果沒有可以使用預設值或 Null,則 Load 方法會擲回例外狀況。 如果未提供任何特定的預設值,此方法會 Load 使用 Null 值做為隱含的預設值。

在考慮方法在數據作業方面的行為 Load 之前,請考慮 中的每個 DataTable 數據列都會維護每個數據行的目前值和原始值。 這些值可能相等,或者如果數據列中的數據在填滿 DataTable之後已經變更,則這些值可能會不同。 如需詳細資訊,請參閱 數據列狀態和數據列版本

在此方法呼叫中,指定的 LoadOption 參數會影響傳入數據的處理。 Load 方法應該如何處理與現有數據列具有相同主鍵的載入數據列? 它應該修改目前的值、原始值或兩者? 這些問題等等是由 參數所 loadOption 控制。

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

就事件作業而言,事件 RowChanging 會在變更每個數據列之前發生,而且 RowChanged 事件會在每個數據列變更之後發生。 在每個案例中, Action 傳遞至事件處理程式之 DataRowChangeEventArgs 實例的 屬性都包含與事件相關聯之特定動作的相關信息。 此動作值會根據載入作業之前的數據列狀態而有所不同。 在每個案例中,都會發生這兩個事件,而且每個事件的動作都相同。 動作可以套用至每個數據列的目前或原始版本,或兩者,視目前的數據列狀態而定。

下表顯示使用每個 LoadOption 值呼叫時 Load 方法的行為,也會顯示值如何與所載入數據列的數據列狀態互動。 最後一個數據列 (標示為「 (不存在) 」) 描述不符合任何現有數據列的連入數據列行為。 此表格中的每個儲存格都會描述數據列內欄位的目前和原始值,以及 DataRowState 方法完成後的值 Load

現有的 DataRowState Upsert OverwriteChanges PreserveChanges (預設行為)
已新增 Current = <Incoming>

原始 = -<無法使用>

狀態 = <已新增>

RowAction = 變更
Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal
目前 = <現有>

原始 = <傳入>

State = <Modified>

RowAction = ChangeOriginal
修改日期 Current = <Incoming>

原始 = <現有>

State = <Modified>

RowAction = 變更
Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal
目前 = <現有>

原始 = <傳入>

State = <Modified>

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

Current = ---

原始 = <現有>

State = <Deleted>

(新增具有下列特性的新數據列)

Current = <Incoming>

原始 = <無法使用>

狀態 = <已新增>

RowAction = Add
復原刪除和

Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal
目前 = <無法使用>

原始 = <傳入>

State = <Deleted>

RowAction = ChangeOriginal
未變更 Current = <Incoming>

原始 = <現有>

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

狀態 = <未變更>

RowAction = Nothing

Else

State = <Modified>

RowAction = 變更
Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal
不存在) Current = <Incoming>

原始 = <無法使用>

狀態 = <已新增>

RowAction = Add
Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal

中的DataColumn值可以透過使用 和等ReadOnlyAutoIncrement屬性來限制。 方法 Load 會以與數據行屬性所定義的行為一致的方式來處理這類數據行。 上的 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,以資料來源的值填滿 IDataReader,使用錯誤處理委派。

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);
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,提供結果集。

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具有架構,但與載入的架構不相容。 方法 Load 會擲回與嘗試將數據載入不相容架構時所發生之特定錯誤的例外狀況。
架構相容,但載入的結果集架構包含 中不存在 DataTable的數據行。 方法 Load 會將額外的數據行 () 新增至 DataTable的架構。 如果 中 DataTable 對應的數據行和載入的結果集與值不相容,方法會擲回例外狀況。 方法也會從所有新增數據行的結果集中擷取條件約束資訊。 除了主鍵條件約束的情況之外,只有在目前 DataTable 未在載入作業開始時包含任何數據行時,才會使用此條件約束資訊。
架構相容,但載入的結果集架構包含的數據行少於 DataTable 如果遺漏的數據行具有已定義的預設值,或數據行的數據類型可為 Null, Load 則方法允許加入數據列,並取代遺漏數據行的預設或 Null 值。 如果沒有可以使用預設值或 Null,則 Load 方法會擲回例外狀況。 如果未提供任何特定的預設值,此方法會 Load 使用 Null 值做為隱含的預設值。

在考慮方法在數據作業方面的行為 Load 之前,請考慮 中的每個 DataTable 數據列都會維護每個數據行的目前值和原始值。 這些值可能相等,或者如果數據列中的數據在填滿 DataTable之後已經變更,則這些值可能會不同。 如需詳細資訊,請參閱 數據列狀態和數據列版本

在此方法呼叫中,指定的 LoadOption 參數會影響傳入數據的處理。 Load 方法應該如何處理與現有數據列具有相同主鍵的載入數據列? 它應該修改目前的值、原始值或兩者? 這些問題等等是由 參數所 loadOption 控制。

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

就事件作業而言,事件 RowChanging 會在變更每個數據列之前發生,而且 RowChanged 事件會在每個數據列變更之後發生。 在每個案例中, Action 傳遞至事件處理程式之 DataRowChangeEventArgs 實例的 屬性都包含與事件相關聯之特定動作的相關信息。 此動作值會根據載入作業之前的數據列狀態而有所不同。 在每個案例中,都會發生這兩個事件,而且每個事件的動作都相同。 動作可以套用至每個數據列的目前或原始版本,或兩者,視目前的數據列狀態而定。

下表顯示使用每個 LoadOption 值呼叫時 Load 方法的行為,也會顯示值如何與所載入數據列的數據列狀態互動。 最後一個數據列 (標示為「 (不存在) 」) 描述不符合任何現有數據列的連入數據列行為。 此表格中的每個儲存格都會描述數據列內欄位的目前和原始值,以及 DataRowState 方法完成後的值 Load

現有的 DataRowState Upsert OverwriteChanges PreserveChanges (預設行為)
已新增 Current = <Incoming>

原始 = -<無法使用>

狀態 = <已新增>

RowAction = 變更
Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal
目前 = <現有>

原始 = <傳入>

State = <Modified>

RowAction = ChangeOriginal
修改日期 Current = <Incoming>

原始 = <現有>

State = <Modified>

RowAction = 變更
Current = <Incoming>

原始 = <傳入>

狀態 = <未變更>

RowAction = ChangeCurrentAndOriginal
目前 = <現有>

Original = <Incoming>

State = <Modified>

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

目前 = ---

Original = <Existing>

State = <Deleted>

(新增具有下列特性的新數據列)

目前 = <傳入>

Original = <無法使用>

State = <已新增>

RowAction = 新增
復原刪除和

目前 = <傳入>

Original = <Incoming>

State = <未變更>

RowAction = ChangeCurrentAndOriginal
目前 = <無法使用>

Original = <Incoming>

State = <Deleted>

RowAction = ChangeOriginal
未變更 目前 = <傳入>

Original = <Existing>

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

State = <未變更>

RowAction = Nothing

Else

State = <Modified>

RowAction = 變更
目前 = <傳入>

Original = <Incoming>

State = <未變更>

RowAction = ChangeCurrentAndOriginal
目前 = <傳入>

Original = <Incoming>

State = <未變更>

RowAction = ChangeCurrentAndOriginal
不存在) 目前 = <傳入>

Original = <無法使用>

State = <已新增>

RowAction = 新增
目前 = <傳入>

Original = <Incoming>

State = <未變更>

RowAction = ChangeCurrentAndOriginal
目前 = <傳入>

Original = <Incoming>

State = <未變更>

RowAction = ChangeCurrentAndOriginal

中的DataColumn值可以使用 和 AutoIncrementReadOnly屬性來限制。 方法會 Load 以與數據行屬性所定義的行為一致的方式來處理這類數據行。 上的 DataColumn 只讀條件約束僅適用於記憶體中發生的變更。 Load方法會視需要覆寫唯讀數據行值。

如果您在呼叫 Load 方法時指定 OverwriteChanges 或 PreserveChanges 選項,則假設傳入的數據來自 DataTable的主要數據源,而 DataTable 會追蹤變更,而且可以將變更傳播回數據源。 如果您選取 Upsert 選項,則會假設資料來自其中一個次要數據源,例如仲介層元件所提供的數據,可能是由用戶改變。 在此情況下,假設意圖是從中的 DataTable一或多個數據源匯總數據,然後或許將數據傳播回主要數據源。 參數 LoadOption 用於判斷要用於主鍵比較之數據列的特定版本。 下表提供詳細數據。

載入選項 用於主鍵比較的 DataRow 版本
OverwriteChanges 原始版本,如果存在,則為 ,否則為目前版本
PreserveChanges 原始版本,如果存在,則為 ,否則為目前版本
Upsert 目前版本,如果存在,則為原始版本

參數 errorHandlerFillErrorEventHandler 委派,參考載入數據時發生錯誤時所呼叫的程式。 FillErrorEventArgs傳遞至程式的參數提供屬性,可讓您擷取所發生錯誤的相關信息、目前的數據列,以及DataTable正在填入的資訊。 使用此委派機制,而不是更簡單的 try/catch 區塊,可讓您判斷錯誤、處理情況,並視需要繼續處理。 參數 FillErrorEventArgs 提供 Continue 屬性:將此屬性設定為 true ,以指出您已處理錯誤,並想要繼續處理。 將屬性設定為 false ,表示您想要停止處理。 請注意,將 屬性設定為 false 會導致觸發問題的程式代碼擲回例外狀況。

另請參閱

適用於