DataTable.Load メソッド

定義

指定された DataTable を使用し、IDataReader にデータ ソースからの値を設定します。Fills a DataTable with values from a data source using the supplied IDataReader. DataTable が既に行を含んでいる場合、データ ソースからの受信データは既存の行にマージされます。If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows.

オーバーロード

Load(IDataReader)

指定された DataTable を使用し、IDataReader にデータ ソースからの値を設定します。Fills a DataTable with values from a data source using the supplied IDataReader. DataTable が既に行を含んでいる場合、データ ソースからの受信データは既存の行にマージされます。If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows.

Load(IDataReader, LoadOption)

指定された DataTable を使用し、IDataReader にデータ ソースからの値を設定します。Fills a DataTable with values from a data source using the supplied IDataReader. DataTable が既に行を含んでいる場合、loadOption パラメーターの値に従って、データ ソースからの受信データは既存の行にマージされます。If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows according to the value of the loadOption parameter.

Load(IDataReader, LoadOption, FillErrorEventHandler)

エラー処理デリゲートを使用し、指定された DataTable を使用して、IDataReader にデータ ソースからの値を設定します。Fills a DataTable with values from a data source using the supplied IDataReader using an error-handling delegate.

次の例は、Load メソッドの呼び出しに関連するいくつかの問題を示しています。The following example demonstrates several of the issues involved with calling the Load method. まず、この例では、読み込まれた IDataReaderからのスキーマの推論、互換性のないスキーマの処理、不足または追加の列を持つスキーマなど、スキーマの問題に焦点を当てています。First, the example focuses on schema issues, including inferring a schema from the loaded IDataReader, and then handling incompatible schemas, and schemas with missing or additional columns. この例では、さまざまな読み込みオプションの処理など、データの問題に焦点を当てています。The example then focuses on data issues, including handling the various loading options.

注意

この例では、Loadのオーバーロードされたバージョンのいずれかを使用する方法を示します。This example shows how to use one of the overloaded versions of Load. 使用できるその他の例については、個々のオーバーロードに関するトピックを参照してください。For other examples that might be available, see the individual overload topics.

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) に追加することを中心として、いくつかの一般的なシナリオで使用できます。The Load method can be used in several common scenarios, all centered around getting data from a specified data source and adding it to the current data container (in this case, a DataTable). これらのシナリオでは、DataTableの標準の使用方法について説明し、その更新とマージの動作について説明します。These scenarios describe standard usage for a DataTable, describing its update and merge behavior.

1つのプライマリデータソースと同期または更新する DataTableA DataTable synchronizes or updates with a single primary data source. DataTable によって変更が追跡され、プライマリデータソースとの同期が可能になります。The DataTable tracks changes, allowing synchronization with the primary data source. さらに、1つまたは複数のセカンダリデータソースからの増分データを受け取ることが DataTable ます。In addition, a DataTable can accept incremental data from one or more secondary data sources. DataTable は、セカンダリデータソースとの同期を許可するために変更を追跡する責任はありません。The DataTable isn't responsible for tracking changes in order to allow synchronization with the secondary data source.

これらの2つの仮想データソースを指定すると、ユーザーは次のいずれかの動作を必要とする可能性があります。Given these two hypothetical data sources, a user is likely to require one of the following behaviors:

  • プライマリデータソースから DataTable を初期化します。Initialize DataTable from a primary data source. このシナリオでは、ユーザーは、プライマリデータソースの値を使用して空の DataTable を初期化する必要があります。In this scenario, the user wants to initialize an empty DataTable with values from the primary data source. その後、ユーザーが変更をプライマリデータソースに反映する予定です。Later the user intends to propagate changes back to the primary data source.

  • 変更を保持し、プライマリデータソースから再同期します。Preserve changes and re-synchronize from the primary data source. このシナリオでは、ユーザーは前のシナリオで入力した DataTable を取得し、プライマリデータソースとの増分同期を実行して、DataTableに加えられた変更を保持する必要があります。In this scenario, the user wants to take the DataTable filled in the previous scenario and perform an incremental synchronization with the primary data source, preserving modifications made in the DataTable.

  • セカンダリデータソースからの増分データフィード。Incremental data feed from secondary data sources. このシナリオでは、ユーザーは1つまたは複数のセカンダリデータソースから変更をマージし、それらの変更をプライマリデータソースに反映させます。In this scenario, the user wants to merge changes from one or more secondary data sources, and propagate those changes back to the primary data source.

Load メソッドを使用すると、すべてのシナリオを可能にすることができます。The Load method makes all these scenarios possible. このメソッドのオーバーロードの1つだけでなく、読み込みオプションパラメーターを指定して、DataTable 内の行が読み込まれている行とどのように結合されるかを示すことができます。All but one of the overloads for this method allows you to specify a load option parameter, indicating how rows already in a DataTable combine with rows being loaded. (動作の指定を許可しないオーバーロードでは、既定の load オプションが使用されます)。次の表では、LoadOption 列挙型によって提供される3つの読み込みオプションについて説明します。(The overload that doesn't allow you to specify the behavior uses the default load option.) The following table describes the three load options provided by the LoadOption enumeration. どちらの場合も、説明は、受信データの行の主キーが既存の行の主キーと一致する場合の動作を示します。In each case, the description indicates the behavior when the primary key of a row in the incoming data matches the primary key of an existing row.

Load オプションLoad Option 説明Description
PreserveChanges (既定値)PreserveChanges (default) 受信した行の値を使用して、行の元のバージョンを更新します。Updates the original version of the row with the value of the incoming row.
OverwriteChanges 行の現在のバージョンと元のバージョンを、受信した行の値で更新します。Updates the current and original versions of the row with the value of the incoming row.
Upsert 行の現在のバージョンを、受信した行の値で更新します。Updates the current version of the row with the value of the incoming row.

一般に、PreserveChanges オプションと OverwriteChanges オプションは、ユーザーが DataSet とその変更をプライマリデータソースと同期する必要があるシナリオを対象としています。In general, the PreserveChanges and OverwriteChanges options are intended for scenarios in which the user needs to synchronize the DataSet and its changes with the primary data source. Upsert オプションを選択すると、1つまたは複数のセカンダリデータソースからの変更を簡単に集計できます。The Upsert option facilitates aggregating changes from one or more secondary data sources.

Load(IDataReader)

指定された DataTable を使用し、IDataReader にデータ ソースからの値を設定します。Fills a DataTable with values from a data source using the supplied IDataReader. DataTable が既に行を含んでいる場合、データ ソースからの受信データは既存の行にマージされます。If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows.

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

結果セットを提供する IDataReaderAn IDataReader that provides a result set.

次の例は、Load メソッドの呼び出しに関連するいくつかの問題を示しています。The following example demonstrates several of the issues involved with calling the Load method. まず、この例では、読み込まれた IDataReaderからのスキーマの推論、互換性のないスキーマの処理、不足または追加の列を持つスキーマなど、スキーマの問題に焦点を当てています。First, the example focuses on schema issues, including inferring a schema from the loaded IDataReader, and then handling incompatible schemas, and schemas with missing or additional columns. この例では、Load メソッドを呼び出し、読み込み操作の前後にデータを表示します。The example then calls the Load method, displaying the data both before and after the load operation.

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から最初の結果セットを使用し、正常に完了した後、リーダーの位置を次の結果セットに設定します (存在する場合)。The Load method consumes the first result set from the loaded IDataReader, and after successful completion, sets the reader's position to the next result set, if any. データを変換する場合、Load メソッドは、DbDataAdapter.Fill メソッドと同じ変換規則を使用します。When converting data, the Load method uses the same conversion rules as the DbDataAdapter.Fill method.

Load メソッドでは、IDataReader インスタンスからデータを読み込むときに、スキーマ、データ、およびイベント操作という3つの特定の問題を考慮する必要があります。The Load method must take into account three specific issues when loading the data from an IDataReader instance: schema, data, and event operations. スキーマを使用する場合、Load 方法では、次の表に示すような条件が発生する可能性があります。When working with the schema, the Load method may encounter conditions as described in the following table. データが含まれていない場合でも、インポートされたすべての結果セットに対してスキーマ操作が行われます。The schema operations take place for all imported result sets, even those containing no data.

条件Condition 動作Behavior
DataTable にはスキーマがありません。The DataTable has no schema. Load メソッドは、インポートされた IDataReaderからの結果セットに基づいてスキーマを推測します。The Load method infers the schema based on the result set from the imported IDataReader.
DataTable にはスキーマがありますが、読み込まれたスキーマと互換性がありません。The DataTable has a schema, but it is incompatible with the loaded schema. Load メソッドは、互換性のないスキーマにデータを読み込もうとしたときに発生する特定のエラーに対応する例外をスローします。The Load method throws an exception corresponding to the particular error that occurs when attempting to load data into the incompatible schema.
スキーマには互換性がありますが、読み込まれた結果セットのスキーマには、DataTableに存在しない列が含まれています。The schemas are compatible, but the loaded result set schema contains columns that do not exist in the DataTable. Load メソッドは、DataTableのスキーマに余分な列を追加します。The Load method adds the extra columns to DataTable's schema. DataTable および読み込まれた結果セット内の対応する列が値と互換性がない場合、メソッドは例外をスローします。The method throws an exception if corresponding columns in the DataTable and the loaded result set are not value compatible. また、このメソッドは、追加されたすべての列の結果セットから制約情報を取得します。The method also retrieves constraint information from the result set for all added columns. Primary Key 制約の場合を除き、この制約情報は、現在の DataTable に読み込み操作の開始時に列が含まれていない場合にのみ使用されます。Except for the case of Primary Key constraint, this constraint information is used only if the current DataTable does not contain any columns at the start of the load operation.
スキーマには互換性がありますが、読み込まれた結果セットのスキーマには、DataTableよりも多くの列が含まれます。The schemas are compatible, but the loaded result set schema contains fewer columns than does the DataTable. 存在しない列に既定値が定義されているか、列のデータ型が null 値を許容している場合、Load メソッドでは、欠落している列の既定値または null 値を置き換えることで行を追加できます。If a missing column has a default value defined or the column's data type is nullable, the Load method allows the rows to be added, substituting the default or null value for the missing column. 既定値または null を使用できない場合、Load メソッドは例外をスローします。If no default value or null can be used, then the Load method throws an exception. 特定の既定値が指定されていない場合、Load メソッドでは、暗黙的な既定値として null 値が使用されます。If no specific default value has been supplied, the Load method uses the null value as the implied default value.

データ操作の観点から Load 手法の動作を検討する前に、DataTable 内の各行が各列の現在の値と元の値の両方を保持することを検討してください。Before considering the behavior of the Load method in terms of data operations, consider that each row within a DataTable maintains both the current value and the original value for each column. これらの値は等価である場合もあれば、DataTableの入力後に行のデータが変更されている場合は異なる場合があります。These values may be equivalent, or may be different if the data in the row has been changed since filling the DataTable. 詳細については、「行の状態と行のバージョン」を参照してください。For more information, see Row States and Row Versions.

このバージョンの Load メソッドは、各行の現在の値を保持して、元の値をそのまま残します。This version of the Load method attempts to preserve the current values in each row, leaving the original value intact. (受信データの動作を細かく制御する必要がある場合は、「DataTable.Load」を参照してください)。既存の行と受信した行に対応する主キーの値が含まれている場合、行は現在の行の状態の値を使用して処理されます。それ以外の場合は、新しい行として扱われます。(If you want finer control over the behavior of incoming data, see DataTable.Load.) If the existing row and the incoming row contain corresponding primary key values, the row is processed using its current row state value, otherwise it's treated as a new row.

イベント操作に関しては、各行が変更される前に RowChanging イベントが発生し、各行が変更された後に RowChanged イベントが発生します。In terms of event operations, the RowChanging event occurs before each row is changed, and the RowChanged event occurs after each row has been changed. どちらの場合も、イベントハンドラーに渡される DataRowChangeEventArgs インスタンスの Action プロパティには、イベントに関連付けられている特定のアクションに関する情報が含まれます。In each case, the Action property of the DataRowChangeEventArgs instance passed to the event handler contains information about the particular action associated with the event. このアクション値は、読み込み操作の前の行の状態によって異なります。This action value depends on the state of the row before the load operation. どちらの場合も、両方のイベントが発生し、アクションはそれぞれに対して同じです。In each case, both events occur, and the action is the same for each. 現在の行の状態に応じて、各行の現在のバージョンまたは元のバージョンのいずれかまたは両方にアクションを適用できます。The action may be applied to either the current or original version of each row, or both, depending on the current row state.

次の表に、Load メソッドの動作を示します。The following table displays behavior for the Load method. 最後の行 ("(存在しない)") には、既存の行と一致しない受信行の動作が記述されています。The final row (labeled "(Not present)") describes the behavior for incoming rows that don't match any existing row. この表の各セルでは、行内のフィールドの現在の値と元の値、および Load メソッドが完了した後の値の DataRowState について説明しています。Each cell in this table describes the current and original value for a field within a row, along with the DataRowState for the value after the Load method has completed. この場合、メソッドでは load オプションを指定することはできず、既定の PreserveChangesを使用します。In this case, the method doesn't allow you to indicate the load option, and uses the default, PreserveChanges.

既存の DataRowStateExisting DataRowState Load メソッドの後の値、およびイベントアクションValues after Load method, and event action
追加Added Current = 既存の > を <Current = <Existing>

Original = <受信 >Original = <Incoming>

状態 = <変更 >State = <Modified>

RowAction = ChangeOriginalRowAction = ChangeOriginal
変更日時Modified Current = 既存の > を <Current = <Existing>

Original = <受信 >Original = <Incoming>

状態 = <変更 >State = <Modified>

RowAction = ChangeOriginalRowAction = ChangeOriginal
DeletedDeleted 現在の = <使用できません >Current = <Not available>

Original = <受信 >Original = <Incoming>

状態 = <削除されました >State = <Deleted>

RowAction = ChangeOriginalRowAction = ChangeOriginal
UnchangedUnchanged Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
(存在しない)(Not present) Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal

DataColumn 内の値は、ReadOnlyAutoIncrementなどのプロパティを使用して制限できます。Values in a DataColumn can be constrained through use of properties such as ReadOnly and AutoIncrement. Load メソッドは、列のプロパティで定義されている動作と一貫性のある方法で、このような列を処理します。The Load method handles such columns in a manner that is consistent with the behavior defined by the column's properties. DataColumn の読み取り専用制約は、メモリ内で発生した変更に対してのみ適用されます。The read only constraint on a DataColumn is applicable only for changes that occur in memory. Load メソッドは、必要に応じて、読み取り専用の列の値を上書きします。The Load method's overwrites the read-only column values, if needed.

現在の行を受信した行と比較するために使用する主キーフィールドのバージョンを決定するために、Load メソッドでは、行に存在する場合は、元のバージョンの primary key 値が使用されます。To determine which version of the primary key field to use for comparing the current row with an incoming row, the Load method uses the original version of the primary key value within a row, if it exists. それ以外の場合、Load メソッドは主キーフィールドの現在のバージョンを使用します。Otherwise, the Load method uses the current version of the primary key field.

こちらもご覧ください

Load(IDataReader, LoadOption)

指定された DataTable を使用し、IDataReader にデータ ソースからの値を設定します。Fills a DataTable with values from a data source using the supplied IDataReader. DataTable が既に行を含んでいる場合、loadOption パラメーターの値に従って、データ ソースからの受信データは既存の行にマージされます。If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows according to the value of the loadOption parameter.

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

パラメーター

reader
IDataReader

1 つ以上の結果セットを含む IDataReaderAn IDataReader that provides one or more result sets.

loadOption
LoadOption

LoadOption 列挙体の値。DataTable に既に含まれている行を同じ主キーを持つ受信した行と結合する方法を示します。A value from the LoadOption enumeration that indicates how rows already in the DataTable are combined with incoming rows that share the same primary key.

次の例は、Load メソッドの呼び出しに関連するいくつかの問題を示しています。The following example demonstrates several of the issues involved with calling the Load method. まず、この例では、読み込まれた IDataReaderからのスキーマの推論、互換性のないスキーマの処理、不足または追加の列を持つスキーマなど、スキーマの問題に焦点を当てています。First, the example focuses on schema issues, including inferring a schema from the loaded IDataReader, and then handling incompatible schemas, and schemas with missing or additional columns. この例では、さまざまな読み込みオプションの処理など、データの問題に焦点を当てています。The example then focuses on data issues, including handling the various loading options.

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から最初の結果セットを使用し、正常に完了した後、リーダーの位置を次の結果セットに設定します (存在する場合)。The Load method consumes the first result set from the loaded IDataReader, and after successful completion, sets the reader's position to the next result set, if any. データを変換する場合、Load メソッドは、Fill メソッドと同じ変換規則を使用します。When converting data, the Load method uses the same conversion rules as the Fill method.

Load メソッドでは、IDataReader インスタンスからデータを読み込むときに、スキーマ、データ、およびイベント操作という3つの特定の問題を考慮する必要があります。The Load method must take into account three specific issues when loading the data from an IDataReader instance: schema, data, and event operations. スキーマを使用する場合、Load 方法では、次の表に示すような条件が発生する可能性があります。When working with the schema, the Load method may encounter conditions as described in the following table. データが含まれていない場合でも、インポートされたすべての結果セットに対してスキーマ操作が行われます。The schema operations take place for all imported result sets, even those containing no data.

条件Condition 動作Behavior
DataTable にはスキーマがありません。The DataTable has no schema. Load メソッドは、インポートされた IDataReaderからの結果セットに基づいてスキーマを推測します。The Load method infers the schema based on the result set from the imported IDataReader.
DataTable にはスキーマがありますが、読み込まれたスキーマと互換性がありません。The DataTable has a schema, but it is incompatible with the loaded schema. Load メソッドは、互換性のないスキーマにデータを読み込もうとしたときに発生する特定のエラーに対応する例外をスローします。The Load method throws an exception corresponding to the particular error that occurs when attempting to load data into the incompatible schema.
スキーマには互換性がありますが、読み込まれた結果セットのスキーマには、DataTableに存在しない列が含まれています。The schemas are compatible, but the loaded result set schema contains columns that don't exist in the DataTable. Load メソッドは、DataTableのスキーマに余分な列を追加します。The Load method adds the extra columns to DataTable's schema. DataTable および読み込まれた結果セット内の対応する列が値と互換性がない場合、メソッドは例外をスローします。The method throws an exception if corresponding columns in the DataTable and the loaded result set are not value compatible. また、このメソッドは、追加されたすべての列の結果セットから制約情報を取得します。The method also retrieves constraint information from the result set for all added columns. Primary Key 制約の場合を除き、この制約情報は、現在の DataTable に読み込み操作の開始時に列が含まれていない場合にのみ使用されます。Except for the case of Primary Key constraint, this constraint information is used only if the current DataTable does not contain any columns at the start of the load operation.
スキーマには互換性がありますが、読み込まれた結果セットのスキーマには、DataTableよりも多くの列が含まれます。The schemas are compatible, but the loaded result set schema contains fewer columns than does the DataTable. 存在しない列に既定値が定義されているか、列のデータ型が null 値を許容している場合、Load 方法では、欠落している列の既定値または null 値を置き換えることで行を追加できます。If a missing column has a default value defined or the column's data type is nullable, the Load method allows the rows to be added, substituting the default or null value for the missing column. 既定値または null を使用できない場合、Load メソッドは例外をスローします。If no default value or null can be used, then the Load method throws an exception. 特定の既定値が指定されていない場合、Load メソッドは、暗黙的な既定値として null 値を使用します。If no specific default value has been supplied, the Load method uses the null value as the implied default value.

データ操作の観点から Load 手法の動作を検討する前に、DataTable 内の各行が各列の現在の値と元の値の両方を保持することを検討してください。Before considering the behavior of the Load method in terms of data operations, consider that each row within a DataTable maintains both the current value and the original value for each column. これらの値は等価である場合もあれば、DataTableの入力後に行のデータが変更されている場合は異なる場合があります。These values may be equivalent, or may be different if the data in the row has been changed since filling the DataTable. 詳細については、「行の状態と行のバージョン」を参照してください。See Row States and Row Versions for more information.

このメソッド呼び出しでは、指定された LoadOption パラメーターが受信データの処理に影響を及ぼします。In this method call, the specified LoadOption parameter influences the processing of the incoming data. Load メソッドが、既存の行と同じ主キーを持つ行の読み込みをどのように処理するかを指定します。How should the Load method handle loading rows that have the same primary key as existing rows? 現在の値、元の値、またはその両方を変更する必要がありますか。Should it modify current values, original values, or both? これらの問題は、loadOption パラメーターによって制御されます。These issues, and more, are controlled by the loadOption parameter.

既存の行と受信した行に対応する主キーの値が含まれている場合、行は現在の行の状態の値を使用して処理されます。それ以外の場合は、新しい行として扱われます。If the existing row and the incoming row contain corresponding primary key values, the row is processed using its current row state value, otherwise it's treated as a new row.

イベント操作に関しては、各行が変更される前に RowChanging イベントが発生し、各行が変更された後に RowChanged イベントが発生します。In terms of event operations, the RowChanging event occurs before each row is changed, and the RowChanged event occurs after each row has been changed. どちらの場合も、イベントハンドラーに渡される DataRowChangeEventArgs インスタンスの Action プロパティには、イベントに関連付けられている特定のアクションに関する情報が含まれます。In each case, the Action property of the DataRowChangeEventArgs instance passed to the event handler contains information about the particular action associated with the event. このアクション値は、読み込み操作の前の行の状態によって異なります。This action value varies, depending on the state of the row before the load operation. どちらの場合も、両方のイベントが発生し、アクションはそれぞれに対して同じです。In each case, both events occur, and the action is the same for each. 現在の行の状態に応じて、各行の現在のバージョンまたは元のバージョンのいずれかまたは両方にアクションを適用できます。The action may be applied to either the current or original version of each row, or both, depending on the current row state.

次の表は、LoadOption の各値と共に呼び出された場合の Load メソッドの動作と、値が読み込み中の行の行の状態とどのように対話するかを示しています。The following table displays behavior for the Load method when called with each of the LoadOption values, and also shows how the values interact with the row state for the row being loaded. 最後の行 ("(存在しない)") には、既存の行と一致しない受信行の動作が記述されています。The final row (labeled "(Not present)") describes the behavior for incoming rows that don't match any existing row. この表の各セルでは、行内のフィールドの現在の値と元の値、および Load メソッドが完了した後の値の DataRowState について説明しています。Each cell in this table describes the current and original value for a field within a row, along with the DataRowState for the value after the Load method has completed.

既存の DataRowStateExisting DataRowState UpsertUpsert 過剰 Writの場合OverwriteChanges PreserveChanges (既定の動作)PreserveChanges (Default behavior)
追加Added Current = <受信 >Current = <Incoming>

Original =-<使用できません >Original = -<Not available>

State = <追加されました >State = <Added>

RowAction = 変更RowAction = Change
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Current = 既存の > を <Current = <Existing>

Original = <受信 >Original = <Incoming>

状態 = <変更 >State = <Modified>

RowAction = ChangeOriginalRowAction = ChangeOriginal
変更日時Modified Current = <受信 >Current = <Incoming>

Original = 既存の > の <Original = <Existing>

状態 = <変更 >State = <Modified>

RowAction = 変更RowAction = Change
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Current = 既存の > を <Current = <Existing>

Original = <受信 >Original = <Incoming>

状態 = <変更 >State = <Modified>

RowAction = ChangeOriginalRowAction =ChangeOriginal
DeletedDeleted (読み込みは削除された行には影響しません)(Load does not affect deleted rows)

現在の =---Current = ---

Original = 既存の > の <Original = <Existing>

状態 = <削除されました >State = <Deleted>

(新しい行は次の特性で追加されます)(New row is added with the following characteristics)

Current = <受信 >Current = <Incoming>

Original = <使用できません >Original = <Not available>

State = <追加されました >State = <Added>

RowAction = AddRowAction = Add
削除を元に戻すとUndo delete and

Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
現在の = <使用できません >Current = <Not available>

Original = <受信 >Original = <Incoming>

状態 = <削除されました >State = <Deleted>

RowAction = ChangeOriginalRowAction = ChangeOriginal
UnchangedUnchanged Current = <受信 >Current = <Incoming>

Original = 既存の > の <Original = <Existing>

新しい値が既存の値と同じ場合は、If new value is the same as the existing value then

State = <変更されていません >State = <Unchanged>

RowAction = NothingRowAction = Nothing

ElseElse

状態 = <変更 >State = <Modified>

RowAction = 変更RowAction = Change
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
存在しない)Not present) Current = <受信 >Current = <Incoming>

Original = <使用できません >Original = <Not available>

State = <追加されました >State = <Added>

RowAction = AddRowAction = Add
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal

DataColumn 内の値は、ReadOnlyAutoIncrementなどのプロパティを使用して制限できます。Values in a DataColumn can be constrained through use of properties such as ReadOnly and AutoIncrement. Load メソッドは、列のプロパティで定義されている動作と一貫性のある方法で、このような列を処理します。The Load method handles such columns in a manner that is consistent with the behavior defined by the column's properties. DataColumn の読み取り専用制約は、メモリ内で発生した変更に対してのみ適用されます。The read only constraint on a DataColumn is applicable only for changes that occur in memory. Load メソッドは、必要に応じて、読み取り専用の列の値を上書きします。The Load method's overwrites the read-only column values, if needed.

Load メソッドを呼び出すときに OverwriteChanges オプションまたは PreserveChanges オプションを指定した場合、受信データが DataTableのプライマリデータソースから送信され、DataTable が変更を追跡して、変更をデータソースに反映させることができます。If you specify the OverwriteChanges or PreserveChanges options when calling the Load method, then the assumption is made that the incoming data is coming from the DataTable's primary data source, and the DataTable tracks changes and can propagate the changes back to the data source. Upsert オプションを選択した場合、データは、ユーザーによって変更された可能性がある中間層コンポーネントによって提供されるデータなど、セカンダリデータソースのいずれかから送信されるものと見なされます。If you select the Upsert option, it is assumed that the data is coming from one of a secondary data source, such as data provided by a middle-tier component, perhaps altered by a user. この場合、DataTable内の1つ以上のデータソースからデータを集計し、データをプライマリデータソースに反映することが意図されています。In this case, the assumption is that the intent is to aggregate data from one or more data sources in the DataTable, and then perhaps propagate the data back to the primary data source. LoadOption パラメーターは、主キーの比較に使用する行の特定のバージョンを決定するために使用されます。The LoadOption parameter is used for determining the specific version of the row that is to be used for primary key comparison. 次の表に詳細を示します。The table below provides the details.

Load オプションLoad option 主キーの比較に使用される DataRow のバージョンDataRow version used for primary key comparison
OverwriteChanges 元のバージョン (存在する場合)、それ以外の場合は現在のバージョンOriginal version, if it exists, otherwise Current version
PreserveChanges 元のバージョン (存在する場合)、それ以外の場合は現在のバージョンOriginal version, if it exists, otherwise Current version
Upsert 現在のバージョン (存在する場合)、それ以外の場合は元のバージョンCurrent version, if it exists, otherwise Original version

こちらもご覧ください

Load(IDataReader, LoadOption, FillErrorEventHandler)

エラー処理デリゲートを使用し、指定された DataTable を使用して、IDataReader にデータ ソースからの値を設定します。Fills a DataTable with values from a data source using the supplied IDataReader using an error-handling delegate.

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

パラメーター

reader
IDataReader

結果セットを提供する IDataReaderA IDataReader that provides a result set.

loadOption
LoadOption

LoadOption 列挙体の値。DataTable に既に含まれている行を同じ主キーを持つ受信した行と結合する方法を示します。A value from the LoadOption enumeration that indicates how rows already in the DataTable are combined with incoming rows that share the same primary key.

errorHandler
FillErrorEventHandler

データの読み込み中にエラーが発生した場合に呼び出される FillErrorEventHandler デリゲート。A FillErrorEventHandler delegate to call when an error occurs while loading data.

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から最初の結果セットを使用し、正常に完了した後、リーダーの位置を次の結果セットに設定します (存在する場合)。The Load method consumes the first result set from the loaded IDataReader, and after successful completion, sets the reader's position to the next result set, if any. データを変換する場合、Load メソッドは、DbDataAdapter.Fill メソッドと同じ変換規則を使用します。When converting data, the Load method uses the same conversion rules as the DbDataAdapter.Fill method.

Load メソッドでは、IDataReader インスタンスからデータを読み込むときに、スキーマ、データ、およびイベント操作という3つの特定の問題を考慮する必要があります。The Load method must take into account three specific issues when loading the data from an IDataReader instance: schema, data, and event operations. スキーマを使用する場合、Load 方法では、次の表に示すような条件が発生する可能性があります。When working with the schema, the Load method may encounter conditions as described in the following table. データが含まれていない場合でも、インポートされたすべての結果セットに対してスキーマ操作が行われます。The schema operations take place for all imported result sets, even those containing no data.

条件Condition 動作Behavior
DataTable にはスキーマがありません。The DataTable has no schema. Load メソッドは、インポートされた IDataReaderからの結果セットに基づいてスキーマを推測します。The Load method infers the schema based on the result set from the imported IDataReader.
DataTable にはスキーマがありますが、読み込まれたスキーマと互換性がありません。The DataTable has a schema, but it is incompatible with the loaded schema. Load メソッドは、互換性のないスキーマにデータを読み込もうとしたときに発生する特定のエラーに対応する例外をスローします。The Load method throws an exception corresponding to the particular error that occurs when attempting to load data into the incompatible schema.
スキーマには互換性がありますが、読み込まれた結果セットのスキーマには、DataTableに存在しない列が含まれています。The schemas are compatible, but the loaded result set schema contains columns that don't exist in the DataTable. Load メソッドは、DataTableのスキーマに余分な列を追加します。The Load method adds the extra column(s) to DataTable's schema. DataTable および読み込まれた結果セット内の対応する列が値と互換性がない場合、メソッドは例外をスローします。The method throws an exception if corresponding columns in the DataTable and the loaded result set are not value compatible. また、このメソッドは、追加されたすべての列の結果セットから制約情報を取得します。The method also retrieves constraint information from the result set for all added columns. Primary Key 制約の場合を除き、この制約情報は、現在の DataTable に読み込み操作の開始時に列が含まれていない場合にのみ使用されます。Except for the case of Primary Key constraint, this constraint information is used only if the current DataTable does not contain any columns at the start of the load operation.
スキーマには互換性がありますが、読み込まれた結果セットのスキーマには、DataTableよりも多くの列が含まれます。The schemas are compatible, but the loaded result set schema contains fewer columns than does the DataTable. 存在しない列に既定値が定義されているか、列のデータ型が null 値を許容している場合、Load 方法では、欠落している列の既定値または null 値を置き換えることで行を追加できます。If a missing column has a default value defined or the column's data type is nullable, the Load method allows the rows to be added, substituting the default or null value for the missing column. 既定値または null を使用できない場合、Load メソッドは例外をスローします。If no default value or null can be used, then the Load method throws an exception. 特定の既定値が指定されていない場合、Load メソッドは、暗黙的な既定値として null 値を使用します。If no specific default value has been supplied, the Load method uses the null value as the implied default value.

データ操作の観点から Load 手法の動作を検討する前に、DataTable 内の各行が各列の現在の値と元の値の両方を保持することを検討してください。Before considering the behavior of the Load method in terms of data operations, consider that each row within a DataTable maintains both the current value and the original value for each column. これらの値は等価である場合もあれば、DataTableの入力後に行のデータが変更されている場合は異なる場合があります。These values may be equivalent, or may be different if the data in the row has been changed since filling the DataTable. 詳細については、「行の状態と行のバージョン」を参照してください。See Row States and Row Versions for more information.

このメソッド呼び出しでは、指定された LoadOption パラメーターが受信データの処理に影響を及ぼします。In this method call, the specified LoadOption parameter influences the processing of the incoming data. Load メソッドが、既存の行と同じ主キーを持つ行の読み込みをどのように処理するかを指定します。How should the Load method handle loading rows that have the same primary key as existing rows? 現在の値、元の値、またはその両方を変更する必要がありますか。Should it modify current values, original values, or both? これらの問題は、loadOption パラメーターによって制御されます。These issues, and more, are controlled by the loadOption parameter.

既存の行と受信した行に対応する主キーの値が含まれている場合、行は現在の行の状態の値を使用して処理されます。それ以外の場合は、新しい行として扱われます。If the existing row and the incoming row contain corresponding primary key values, the row is processed using its current row state value, otherwise it's treated as a new row.

イベント操作に関しては、各行が変更される前に RowChanging イベントが発生し、各行が変更された後に RowChanged イベントが発生します。In terms of event operations, the RowChanging event occurs before each row is changed, and the RowChanged event occurs after each row has been changed. どちらの場合も、イベントハンドラーに渡される DataRowChangeEventArgs インスタンスの Action プロパティには、イベントに関連付けられている特定のアクションに関する情報が含まれます。In each case, the Action property of the DataRowChangeEventArgs instance passed to the event handler contains information about the particular action associated with the event. このアクション値は、読み込み操作の前の行の状態によって異なります。This action value varies, depending on the state of the row before the load operation. どちらの場合も、両方のイベントが発生し、アクションはそれぞれに対して同じです。In each case, both events occur, and the action is the same for each. 現在の行の状態に応じて、各行の現在のバージョンまたは元のバージョンのいずれかまたは両方にアクションを適用できます。The action may be applied to either the current or original version of each row, or both, depending on the current row state.

次の表は、LoadOption の各値と共に呼び出された場合の Load メソッドの動作と、値が読み込み中の行の行の状態とどのように対話するかを示しています。The following table displays behavior for the Load method when called with each of the LoadOption values, and also shows how the values interact with the row state for the row being loaded. 最後の行 ("(存在しない)") には、既存の行と一致しない受信行の動作が記述されています。The final row (labeled "(Not present)") describes the behavior for incoming rows that don't match any existing row. この表の各セルでは、行内のフィールドの現在の値と元の値、および Load メソッドが完了した後の値の DataRowState について説明しています。Each cell in this table describes the current and original value for a field within a row, along with the DataRowState for the value after the Load method has completed.

既存の DataRowStateExisting DataRowState UpsertUpsert 過剰 Writの場合OverwriteChanges PreserveChanges (既定の動作)PreserveChanges (Default behavior)
追加Added Current = <受信 >Current = <Incoming>

Original =-<使用できません >Original = -<Not available>

State = <追加されました >State = <Added>

RowAction = 変更RowAction = Change
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Current = 既存の > を <Current = <Existing>

Original = <受信 >Original = <Incoming>

状態 = <変更 >State = <Modified>

RowAction = ChangeOriginalRowAction = ChangeOriginal
変更日時Modified Current = <受信 >Current = <Incoming>

Original = 既存の > の <Original = <Existing>

状態 = <変更 >State = <Modified>

RowAction = 変更RowAction = Change
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Current = 既存の > を <Current = <Existing>

Original = <受信 >Original = <Incoming>

状態 = <変更 >State = <Modified>

RowAction = ChangeOriginalRowAction =ChangeOriginal
eletedeleted (読み込みは削除された行には影響しません)(Load does not affect deleted rows)

現在の =---Current = ---

Original = 既存の > の <Original = <Existing>

状態 = <削除されました >State = <Deleted>

(新しい行は次の特性で追加されます)(New row is added with the following characteristics)

Current = <受信 >Current = <Incoming>

Original = <使用できません >Original = <Not available>

State = <追加されました >State = <Added>

RowAction = AddRowAction = Add
削除を元に戻すとUndo delete and

Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
現在の = <使用できません >Current = <Not available>

Original = <受信 >Original = <Incoming>

状態 = <削除されました >State = <Deleted>

RowAction = ChangeOriginalRowAction = ChangeOriginal
UnchangedUnchanged Current = <受信 >Current = <Incoming>

Original = 既存の > の <Original = <Existing>

新しい値が既存の値と同じ場合は、If new value is the same as the existing value then

State = <変更されていません >State = <Unchanged>

RowAction = NothingRowAction = Nothing

ElseElse

状態 = <変更 >State = <Modified>

RowAction = 変更RowAction = Change
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
存在しない)Not present) Current = <受信 >Current = <Incoming>

Original = <使用できません >Original = <Not available>

State = <追加されました >State = <Added>

RowAction = AddRowAction = Add
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Current = <受信 >Current = <Incoming>

Original = <受信 >Original = <Incoming>

State = <変更されていません >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal

DataColumn 内の値は、ReadOnlyAutoIncrementなどのプロパティを使用して制限できます。Values in a DataColumn can be constrained through use of properties such as ReadOnly and AutoIncrement. Load メソッドは、列のプロパティで定義されている動作と一貫性のある方法で、このような列を処理します。The Load method handles such columns in a manner that is consistent with the behavior defined by the column's properties. DataColumn の読み取り専用制約は、メモリ内で発生した変更に対してのみ適用されます。The read only constraint on a DataColumn is applicable only for changes that occur in memory. Load メソッドは、必要に応じて、読み取り専用の列の値を上書きします。The Load method's overwrites the read-only column values, if needed.

Load メソッドを呼び出すときに OverwriteChanges オプションまたは PreserveChanges オプションを指定した場合、受信データが DataTableのプライマリデータソースから送信され、DataTable が変更を追跡して、変更をデータソースに反映させることができます。If you specify the OverwriteChanges or PreserveChanges options when calling the Load method, then the assumption is made that the incoming data is coming from the DataTable's primary data source, and the DataTable tracks changes and can propagate the changes back to the data source. Upsert オプションを選択した場合、データは、ユーザーによって変更された可能性がある中間層コンポーネントによって提供されるデータなど、セカンダリデータソースのいずれかから送信されるものと見なされます。If you select the Upsert option, it is assumed that the data is coming from one of a secondary data source, such as data provided by a middle-tier component, perhaps altered by a user. この場合、DataTable内の1つ以上のデータソースからデータを集計し、データをプライマリデータソースに反映することが意図されています。In this case, the assumption is that the intent is to aggregate data from one or more data sources in the DataTable, and then perhaps propagate the data back to the primary data source. LoadOption パラメーターは、主キーの比較に使用する行の特定のバージョンを決定するために使用されます。The LoadOption parameter is used for determining the specific version of the row that is to be used for primary key comparison. 次の表に詳細を示します。The table below provides the details.

Load オプションLoad option 主キーの比較に使用される DataRow のバージョンDataRow version used for primary key comparison
OverwriteChanges 元のバージョン (存在する場合)、それ以外の場合は現在のバージョンOriginal version, if it exists, otherwise Current version
PreserveChanges 元のバージョン (存在する場合)、それ以外の場合は現在のバージョンOriginal version, if it exists, otherwise Current version
Upsert 現在のバージョン (存在する場合)、それ以外の場合は元のバージョンCurrent version, if it exists, otherwise Original version

errorHandler パラメーターは、データの読み込み中にエラーが発生したときに呼び出されるプロシージャを参照する FillErrorEventHandler デリゲートです。The errorHandler parameter is a FillErrorEventHandler delegate that refers to a procedure that is called when an error occurs while loading data. プロシージャに渡される FillErrorEventArgs パラメーターには、発生したエラー、データの現在の行、および格納されている DataTable に関する情報を取得するためのプロパティが用意されています。The FillErrorEventArgs parameter passed to the procedure provides properties that allow you to retrieve information about the error that occurred, the current row of data, and the DataTable being filled. より単純な try/catch ブロックではなく、このデリゲートメカニズムを使用すると、エラーを特定し、状況を処理し、必要に応じて処理を続行できます。Using this delegate mechanism, rather than a simpler try/catch block, allows you to determine the error, handle the situation, and continue processing if you like. FillErrorEventArgs パラメーターは Continue プロパティを提供します。このプロパティを true に設定して、エラーを処理し、処理を続行することを示します。The FillErrorEventArgs parameter supplies a Continue property: set this property to true to indicate that you have handled the error and wish to continue processing. プロパティを false に設定して、処理を停止することを指定します。Set the property to false to indicate that you wish to halt processing. プロパティを false に設定すると、問題を発生させたコードが例外をスローすることに注意してください。Be aware that setting the property to false causes the code that triggered the problem to throw an exception.

こちらもご覧ください

適用対象