次の方法で共有


DataTable.Load メソッド

定義

指定したIDataReaderを使用して、データ ソースの値をDataTableに入力します。 DataTableに既に行が含まれている場合、データ ソースからの受信データは既存の行とマージされます。

オーバーロード

名前 説明
Load(IDataReader)

指定したIDataReaderを使用して、データ ソースの値をDataTableに入力します。 DataTableに既に行が含まれている場合、データ ソースからの受信データは既存の行とマージされます。

Load(IDataReader, LoadOption)

指定したIDataReaderを使用して、データ ソースの値をDataTableに入力します。 DataTableに既に行が含まれている場合、データ ソースからの受信データは、loadOption パラメーターの値に従って既存の行とマージされます。

Load(IDataReader, LoadOption, FillErrorEventHandler)

エラー処理デリゲートを使用して、指定されたIDataReaderを使用して、データ ソースの値をDataTableに入力します。

次の例では、 Load メソッドの呼び出しに関連するいくつかの問題を示します。 最初に、この例では、読み込まれた IDataReaderからスキーマを推論し、互換性のないスキーマと、不足している列または追加の列を含むスキーマを処理するなど、スキーマの問題に重点を置いています。 その後、さまざまな読み込みオプションの処理など、データの問題に焦点を当てます。

この例では、 Loadのオーバーロードされたバージョンの 1 つを使用する方法を示します。 使用可能なその他の例については、個々のオーバーロードに関するトピックを参照してください。

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.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs

指定したIDataReaderを使用して、データ ソースの値をDataTableに入力します。 DataTableに既に行が含まれている場合、データ ソースからの受信データは既存の行とマージされます。

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

パラメーター

reader
IDataReader

結果セットを提供する IDataReader

属性

次の例では、 Load メソッドの呼び出しに関連するいくつかの問題を示します。 最初に、この例では、読み込まれた IDataReaderからスキーマを推論し、互換性のないスキーマと、不足している列または追加の列を含むスキーマを処理するなど、スキーマの問題に重点を置いています。 次に、 Load メソッドを呼び出し、読み込み操作の前後の両方にデータを表示します。

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

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

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

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

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

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

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

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

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

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

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

    table = SetupModifiedRows();
    DisplayRowState(table);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  table.Load(reader)
  PrintColumns(table)

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

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

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

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

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

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

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

  table = SetupModifiedRows()
  DisplayRowState(table)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Private Sub PrintColumns( _
   ByVal table As DataTable)

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

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

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

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

注釈

Load メソッドは、読み込まれたIDataReaderから最初の結果セットを使用し、正常に完了した後、リーダーの位置を次の結果セット (ある場合) に設定します。 データを変換する場合、 Load メソッドでは、 DbDataAdapter.Fill メソッドと同じ変換規則が使用されます。

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

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

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

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
変更済み Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
削除済み Current = <Not available>

Original = <Incoming>

State = <Deleted>

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

Original = <Incoming>

State = <Unchanged>

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

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

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

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

こちらもご覧ください

適用対象

Load(IDataReader, LoadOption)

ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs

指定したIDataReaderを使用して、データ ソースの値をDataTableに入力します。 DataTableに既に行が含まれている場合、データ ソースからの受信データは、loadOption パラメーターの値に従って既存の行とマージされます。

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

パラメーター

reader
IDataReader

1 つ以上の結果セットを提供する IDataReader

loadOption
LoadOption

DataTable内の行が同じ主キーを共有する受信行と結合される方法を示す、LoadOption列挙体の値。

属性

次の例では、 Load メソッドの呼び出しに関連するいくつかの問題を示します。 最初に、この例では、読み込まれた IDataReaderからスキーマを推論し、互換性のないスキーマと、不足している列または追加の列を含むスキーマを処理するなど、スキーマの問題に重点を置いています。 その後、さまざまな読み込みオプションの処理など、データの問題に焦点を当てます。

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

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

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

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

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

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

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

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

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

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

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

    table = SetupModifiedRows();
    DisplayRowState(table);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

private static void PerformDemo(LoadOption optionForLoad)
{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  table = SetupModifiedRows()
  DisplayRowState(table)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Private Sub PerformDemo(ByVal optionForLoad As LoadOption)

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

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

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

Private Sub PrintColumns( _
   ByVal table As DataTable)

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

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

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

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

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

注釈

Load メソッドは、読み込まれたIDataReaderから最初の結果セットを使用し、正常に完了した後、リーダーの位置を次の結果セット (ある場合) に設定します。 データを変換する場合、 Load メソッドでは、 Fill メソッドと同じ変換規則が使用されます。

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

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

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

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

State = <Added>

RowAction = 変更
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
変更済み Current = <Incoming>

Original = <Existing>

State = <Modified>

RowAction = 変更
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

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

Current = ---

Original = <Existing>

State = <Deleted>

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

Current = <Incoming>

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

State = <Added>

RowAction = 追加
元に戻す削除と

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



State = <Modified>

RowAction = 変更
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

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

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

State = <Added>

RowAction = 追加
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

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

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

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

こちらもご覧ください

適用対象

Load(IDataReader, LoadOption, FillErrorEventHandler)

ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs

エラー処理デリゲートを使用して、指定されたIDataReaderを使用して、データ ソースの値をDataTableに入力します。

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

パラメーター

reader
IDataReader

結果セットを提供する IDataReader

loadOption
LoadOption

DataTable内の行が同じ主キーを共有する受信行と結合される方法を示す、LoadOption列挙体の値。

errorHandler
FillErrorEventHandler

データの読み込み中にエラーが発生したときに呼び出す FillErrorEventHandler デリゲート。

属性

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Private Sub PrintColumns( _
   ByVal table As DataTable)

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

注釈

Load メソッドは、読み込まれたIDataReaderから最初の結果セットを使用し、正常に完了した後、リーダーの位置を次の結果セット (ある場合) に設定します。 データを変換する場合、 Load メソッドでは、 DbDataAdapter.Fill メソッドと同じ変換規則が使用されます。

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

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

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

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

State = <Added>

RowAction = 変更
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
変更済み Current = <Incoming>

Original = <Existing>

State = <Modified>

RowAction = 変更
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

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

Current = ---

Original = <Existing>

State = <Deleted>

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

Current = <Incoming>

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

State = <Added>

RowAction = 追加
元に戻す削除と

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



State = <Modified>

RowAction = 変更
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

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

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

State = <Added>

RowAction = 追加
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

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

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

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

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

こちらもご覧ください

適用対象