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からスキーマを推論し、互換性のないスキーマと、不足している列または追加の列を含むスキーマを処理するなど、スキーマの問題に焦点を当てています。 次に、さまざまな読み込みオプションの処理など、データの問題に焦点を当てます。

Note

この例では、 のオーバーロードされたバージョンの 1 つを使用する方法を示します 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 、1 つ以上のセカンダリ データ ソースからの増分データを受け入れることもできます。 DataTableは、セカンダリ データ ソースとの同期を許可するために変更を追跡する責任を負いません。

これら 2 つの架空のデータ ソースを考えると、ユーザーは次のいずれかの動作を必要とする可能性があります。

  • プライマリ データ ソースから初期化 DataTable します。 このシナリオでは、ユーザーはプライマリ データ ソースの値を使用して空 DataTable の を初期化したいと考えています。 後で、ユーザーは変更をプライマリ データ ソースに反映する予定です。

  • 変更を保持し、プライマリ データ ソースから再同期します。 このシナリオでは、ユーザーは前のシナリオで入力した を DataTable 取得し、プライマリ データ ソースとの増分同期を実行し、 で DataTable行われた変更を保持したいと考えています。

  • セカンダリ データ ソースからの増分データ フィード。 このシナリオでは、ユーザーは 1 つ以上のセカンダリ データ ソースからの変更をマージし、それらの変更をプライマリ データ ソースに反映したいと考えています。

メソッドを Load 使用すると、これらすべてのシナリオが可能になります。 このメソッドのオーバーロードの 1 つを含め、すべて読み込みオプション パラメーターを指定できます。これは、既に行が読み込まれている行と結合する方法を DataTable 示します。 (動作を指定できないオーバーロードでは、既定の読み込みオプションが使用されます)。次の表では、 列挙体によって LoadOption 提供される 3 つの読み込みオプションについて説明します。 いずれの場合も、入力データの行の主キーが既存の行の主キーと一致する場合の動作が説明に示されます。

読み込みオプション 説明
PreserveChanges (既定値) 受信行の値を使用して、元のバージョンの行を更新します。
OverwriteChanges 受信行の値を使用して、行の現在のバージョンと元のバージョンを更新します。
Upsert 受信行の値を使用して、現在のバージョンの行を更新します。

一般に PreserveChanges 、 オプションと OverwriteChanges オプションは、 とその変更をプライマリ データ ソースと同期 DataSet する必要があるシナリオを対象としています。 オプションを Upsert 使用すると、1 つ以上のセカンダリ データ ソースからの変更の集計が容易になります。

Load(IDataReader)

指定された 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 データを読み込む際に、スキーマ、データ、イベント操作の 3 つの特定の問題を考慮する必要があります。 スキーマを使用する場合、次の 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 変更された後にイベントが発生します。 いずれの場合も、イベント ハンドラーにActionDataRowChangeEventArgs渡されるインスタンスの プロパティには、イベントに関連付けられている特定のアクションに関する情報が含まれます。 このアクション値は、読み込み操作前の行の状態によって異なります。 いずれの場合も、両方のイベントが発生し、アクションはそれぞれ同じです。 アクションは、現在の行の状態に応じて、各行の現在または元のバージョン、またはその両方に適用できます。

次の表に、 メソッドの動作を Load 示します。 最後の行 ("(存在しません)" というラベルが付いた行は、既存の行と一致しない受信行の動作を表します。 この表の各セルでは、行内のフィールドの現在の値と元の値と、 DataRowState メソッドの完了後の値 Load の が記述されます。 この場合、 メソッドでは読み込みオプションを指定できません。既定の を使用します PreserveChanges

既存の DataRowState メソッドとイベント アクションの後 Load の値
追加 Current = <Existing>

元の = <受信>

State = <Modified>

RowAction = ChangeOriginal
修正済み Current = <Existing>

元の = <受信>

State = <Modified>

RowAction = ChangeOriginal
Deleted Current = <Not available>

元の = <受信>

状態 = <削除済み>

RowAction = ChangeOriginal
変更なし Current = <Incoming>

元の = <受信>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
(存在しません) Current = <Incoming>

元の = <受信>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

内のDataColumn値は、 や AutoIncrementなどのReadOnlyプロパティを使用して制限できます。 メソッドは Load 、列のプロパティによって定義された動作と一致する方法で、このような列を処理します。 の DataColumn 読み取り専用制約は、メモリ内で発生する変更にのみ適用されます。 メソッドの は Load 、必要に応じて読み取り専用列の値を上書きします。

現在の行と受信行を比較するために使用する主キー フィールドのバージョンを確認するために、 Load メソッドは行内の元のバージョンの主キー値 (存在する場合) を使用します。 それ以外の場合、メソッドは Load 現在のバージョンの主キー フィールドを使用します。

こちらもご覧ください

適用対象

Load(IDataReader, LoadOption)

指定された 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

1 つ以上の結果セットを含む 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 、インスタンスからデータを読み込むときに、スキーマ、データ、イベント操作という 3 つの特定の問題を 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 変更された後にイベントが発生します。 いずれの場合も、イベント ハンドラーにActionDataRowChangeEventArgs渡されるインスタンスの プロパティには、イベントに関連付けられている特定のアクションに関する情報が含まれます。 このアクション値は、読み込み操作前の行の状態によって異なります。 いずれの場合も、両方のイベントが発生し、アクションはそれぞれ同じです。 アクションは、現在の行の状態に応じて、各行の現在のバージョンまたは元のバージョン、またはその両方に適用できます。

次の表は、各値を使用して呼び出されたときの Load メソッドの LoadOption 動作と、読み込まれる行の行状態と値がどのように相互作用するかを示しています。 最後の行 ("(存在しません)") は、既存の行と一致しない受信行の動作を表します。 この表の各セルは、行内のフィールドの現在の値と元の値と、 DataRowState メソッドが完了した後の値の を Load 表します。

既存の DataRowState Upsert OverwriteChanges PreserveChanges (既定の動作)
追加 Current = <Incoming>

Original = -<Not available>

State = <Added>

RowAction = Change
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
修正済み Current = <Incoming>

Original = <Existing>

State = <Modified>

RowAction = Change
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction =ChangeOriginal
Deleted (読み込みは削除された行には影響しません)

Current = ---

Original = <Existing>

State = <Deleted>

(次の特性を持つ新しい行が追加されます)

Current = <Incoming>

元の = <使用できません>

State = <Added>

RowAction = Add
元に戻す削除と

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Not available>

Original = <Incoming>

State = <Deleted>

RowAction = ChangeOriginal
変更なし Current = <Incoming>

Original = <Existing>

新しい値が既存の値と同じ場合は、

State = <Unchanged>

RowAction = Nothing

Else

State = <Modified>

RowAction = Change
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
存在しません) Current = <Incoming>

元の = <使用できません>

State = <Added>

RowAction = Add
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

内のDataColumn値は、 や AutoIncrementなどのReadOnlyプロパティを使用して制限できます。 メソッドは Load 、列のプロパティによって定義された動作と一致する方法で、このような列を処理します。 の DataColumn 読み取り専用制約は、メモリ内で発生する変更にのみ適用されます。 メソッドの は Load 、必要に応じて読み取り専用の列値を上書きします。

メソッドの呼び出し Load 時に OverwriteChanges または PreserveChanges オプションを指定した場合、受信データがのプライマリ データ ソースから DataTable送信され、DataTable が変更を追跡し、変更をデータ ソースに反映できることを前提とします。 Upsert オプションを選択した場合、データは、中間層コンポーネントによって提供されるデータなど、セカンダリ データ ソースのいずれかから取得されたものと見なされ、ユーザーによって変更される可能性があります。 この場合、意図は、 内 DataTableの 1 つ以上のデータ ソースからデータを集計し、データをプライマリ データ ソースに反映させる可能性があることを前提とします。 パラメーターは LoadOption 、主キー比較に使用される行の特定のバージョンを決定するために使用されます。 次の表に、詳細を示します。

[読み込み] オプション 主キーの比較に使用される DataRow バージョン
OverwriteChanges 元のバージョン (存在する場合)、それ以外の場合は現在のバージョン
PreserveChanges 元のバージョン (存在する場合)、それ以外の場合は現在のバージョン
Upsert 現在のバージョン (存在する場合)、それ以外の場合は元のバージョン

こちらもご覧ください

適用対象

Load(IDataReader, LoadOption, FillErrorEventHandler)

エラー処理デリゲートを使用し、指定された 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 、インスタンスからデータを読み込むときに、スキーマ、データ、イベント操作という 3 つの特定の問題を 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 変更された後にイベントが発生します。 いずれの場合も、イベント ハンドラーにActionDataRowChangeEventArgs渡されるインスタンスの プロパティには、イベントに関連付けられている特定のアクションに関する情報が含まれます。 このアクション値は、読み込み操作前の行の状態によって異なります。 いずれの場合も、両方のイベントが発生し、アクションはそれぞれ同じです。 アクションは、現在の行の状態に応じて、各行の現在のバージョンまたは元のバージョン、またはその両方に適用できます。

次の表は、各値を使用して呼び出されたときの Load メソッドの LoadOption 動作と、読み込まれる行の行状態と値がどのように相互作用するかを示しています。 最後の行 ("(存在しません)") は、既存の行と一致しない受信行の動作を表します。 この表の各セルは、行内のフィールドの現在の値と元の値と、 DataRowState メソッドが完了した後の値の を Load 表します。

既存の DataRowState Upsert OverwriteChanges PreserveChanges (既定の動作)
追加 Current = <Incoming>

Original = -<Not available>

State = <Added>

RowAction = Change
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
修正済み Current = <Incoming>

Original = <Existing>

State = <Modified>

RowAction = Change
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

元の = <受信>

State = <Modified>

RowAction =ChangeOriginal
eleted (読み込みでは削除された行には影響しません)

Current = ---

元の = <既存>

状態 = <削除済み>

(次の特性を持つ新しい行が追加されます)

Current = <Incoming>

元の = <使用できません>

State = <Added>

RowAction = Add
削除と元に戻す

Current = <Incoming>

元の = <受信>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Not available>

元の = <受信>

状態 = <削除済み>

RowAction = ChangeOriginal
変更なし Current = <Incoming>

元の = <既存>

新しい値が既存の値と同じ場合は、

State = <Unchanged>

RowAction = Nothing

Else

State = <Modified>

RowAction = Change
Current = <Incoming>

元の = <受信>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

元の = <受信>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
存在しない) Current = <Incoming>

元の = <使用できません>

State = <Added>

RowAction = Add
Current = <Incoming>

元の = <受信>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

元の = <受信>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

内のDataColumn値は、 や AutoIncrementなどのReadOnlyプロパティを使用して制限できます。 メソッドは Load 、列のプロパティによって定義された動作と一致する方法で、このような列を処理します。 の DataColumn 読み取り専用制約は、メモリ内で発生する変更にのみ適用されます。 メソッドの は Load 、必要に応じて読み取り専用列の値を上書きします。

メソッドの呼び出し Load 時に OverwriteChanges オプションまたは PreserveChanges オプションを指定した場合、受信データは のプライマリ データ ソースから DataTable取得され、DataTable は変更を追跡し、変更をデータ ソースに反映できることを前提とします。 [アップサート] オプションを選択した場合、データは、中間層コンポーネントによって提供されるデータなど、セカンダリ データ ソースのいずれかから取得されたものと見なされ、ユーザーによって変更される可能性があります。 この場合、意図は、 内 DataTableの 1 つ以上のデータ ソースからデータを集計し、そのデータをプライマリ データ ソースに反映することが前提です。 パラメーターは LoadOption 、主キーの比較に使用する行の特定のバージョンを決定するために使用されます。 次の表に、詳細を示します。

[読み込み] オプション 主キーの比較に使用される DataRow バージョン
OverwriteChanges 元のバージョン(存在する場合)、それ以外の場合は現在のバージョン
PreserveChanges 元のバージョン(存在する場合)、それ以外の場合は現在のバージョン
Upsert 現在のバージョン (存在する場合)、それ以外の場合は元のバージョン

パラメーターは errorHandler 、データの FillErrorEventHandler 読み込み中にエラーが発生したときに呼び出されるプロシージャを参照するデリゲートです。 プロシージャに渡されるパラメーターには FillErrorEventArgs 、発生したエラー、現在のデータ行、および入力されている に関する情報を取得できるプロパティが DataTable 用意されています。 このデリゲート メカニズムを使用すると、より単純な try/catch ブロックではなく、エラーを特定し、状況を処理し、必要に応じて処理を続行できます。 パラメーターは FillErrorEventArgs プロパティを Continue 提供します。このプロパティを に true 設定して、エラーを処理し、処理を続行することを示します。 処理を停止することを示すには、 プロパティ false を に設定します。 プロパティを に false 設定すると、問題をトリガーしたコードで例外がスローされることに注意してください。

こちらもご覧ください

適用対象