DataTable.Loadとは? わかりやすく解説

DataTable.Load メソッド (IDataReader, LoadOption)

メモ : このメソッドは、.NET Framework version 2.0新しく追加されたものです。

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

名前空間: System.Data
アセンブリ: System.Data (system.data.dll 内)
構文構文

Public Sub Load ( _
    reader As IDataReader, _
    loadOption As LoadOption _
)
Dim instance As DataTable
Dim reader As IDataReader
Dim loadOption As LoadOption

instance.Load(reader, loadOption)
public void Load (
    IDataReader reader,
    LoadOption loadOption
)
public:
void Load (
    IDataReader^ reader, 
    LoadOption loadOption
)
public void Load (
    IDataReader reader, 
    LoadOption loadOption
)
public function Load (
    reader : IDataReader, 
    loadOption : LoadOption
)

パラメータ

reader

1 つ上の結果セットを含む IDataReader。

loadOption

LoadOption 列挙体の値。DataTable に既に含まれている行を同じ主キーを持つ受信した行と結合する方法示します

解説解説

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 プロパティに、イベント関連付けられている特定のアクションに関する情報格納されます。このアクション値は、読み込み操作の前の行の状態に応じて変わります。どちらの場合でも、両方イベント発生しアクション同じになります現在の行の状態に応じてアクション各行現在のバージョンまたは元のバージョン、あるいは両方バージョン適用されます。

Load メソッドLoadOption の各値を使って呼び出したときの動作次の表に示しますまた、それらの値と読み込む行の行状態との関係も示します。"(存在せず)" と表記され最後の行は、受信した行が既存の行と一致しなかった場合動作表します。この表の各マスに、行内フィールド現在の値と元の値、および Load メソッド完了した後の値の DataRowState を示します

既存の DataRowState

Upsert

OverwriteChanges

PreserveChanges (既定動作)

Added

現在の値 = <Incoming>

元の値 = -<Not available>

状態 = <Added>

RowAction = Change

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Existing>

元の値 = <Incoming>

状態 = <Modified>

RowAction = ChangeOriginal

Modified

現在の値 = <Incoming>

元の値 = <Existing>

状態 = <Modified>

RowAction = Change

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Existing>

元の値 = <Incoming>

状態 = <Modified>

RowAction =ChangeOriginal

Deleted

(削除済みの行は Load メソッド影響を受けません)

現在の値 = ---

元の値 = <Existing>

状態 = <Deleted>

(新しく追加される行は次の特性持ちます)

現在の値 = <Incoming>

元の値 = <Not available>

状態 = <Added>

RowAction = Add

削除元に戻すと、次のようになります

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Not available>

元の値 = <Incoming>

状態 = <Deleted>

RowAction = ChangeOriginal

Unchanged

現在の値 = <Incoming>

元の値 = <Existing>

新しい値が既存の値と同じ場合次のようになります

状態 = <Unchanged>

RowAction = Nothing

それ以外場合次のようになります

状態 = <Modified>

RowAction = Change

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

(存在せず)

現在の値 = <Incoming>

元の値 = <Not available>

状態 = <Added>

RowAction = Add

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

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

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

使用例使用例

Load メソッド呼び出しに関する問題次の例にいくつか示します。この例ではまず、読み込まれIDataReader からのスキーマ推論互換性のないスキーマの処理、行が欠けていたり多すぎたりするスキーマなど、スキーマ問題示します次にさまざまな読み込みオプションの処理など、データ問題示します

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
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);
}
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

DataTable.Load メソッド (IDataReader)

メモ : このメソッドは、.NET Framework version 2.0新しく追加されたものです。

指定されIDataReader使用し、DataTable にデータ ソースからの値を設定しますDataTable が既に行を含んでいる場合データ ソースからの受信データ既存の行にマージされます

名前空間: System.Data
アセンブリ: System.Data (system.data.dll 内)
構文構文

Public Sub Load ( _
    reader As IDataReader _
)
Dim instance As DataTable
Dim reader As IDataReader

instance.Load(reader)
public void Load (
    IDataReader reader
)
public:
void Load (
    IDataReader^ reader
)
public void Load (
    IDataReader reader
)
public function Load (
    reader : IDataReader
)

パラメータ

reader

結果セット提供する IDataReader。

解説解説

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 メソッド後の値とイベント アクション

Added

現在の値 = <Existing>

元の値 = <Incoming>

状態 = <Modified>

RowAction = ChangeOriginal

Modified

現在の値 = <Existing>

元の値 = <Incoming>

状態 = <Modified>

RowAction = ChangeOriginal

Deleted

現在の値 = <Not available>

元の値 = <Incoming>

状態 = <Deleted>

RowAction = ChangeOriginal

Unchanged

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

(存在せず)

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

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

行内主キー値の元のバージョン存在する場合Load メソッドではそれを使用して現在の行と受信した行の比較使用される主キー フィールドバージョン判断しますそれ以外場合Load メソッドでは主キー フィールド現在のバージョン使用されます。

使用例使用例

Load メソッド呼び出しに関する問題次の例にいくつか示します。この例ではまず、読み込まれIDataReader からのスキーマ推論互換性のないスキーマの処理、行が欠けていたり多すぎたりするスキーマなど、スキーマ問題示します次にLoad メソッド呼び出し読み込み操作の前と後のデータ表示します

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
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;
}
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

DataTable.Load メソッド (IDataReader, LoadOption, FillErrorEventHandler)

メモ : このメソッドは、.NET Framework version 2.0新しく追加されたものです。

エラー処理デリゲート使用し指定されIDataReader使用してDataTableデータ ソースからの値を設定します

名前空間: System.Data
アセンブリ: System.Data (system.data.dll 内)
構文構文

Public Overridable Sub Load
 ( _
    reader As IDataReader, _
    loadOption As LoadOption, _
    errorHandler As FillErrorEventHandler _
)
Dim instance As DataTable
Dim reader As IDataReader
Dim loadOption As LoadOption
Dim errorHandler As FillErrorEventHandler

instance.Load(reader, loadOption, errorHandler)
public virtual void Load (
    IDataReader reader,
    LoadOption loadOption,
    FillErrorEventHandler errorHandler
)
public:
virtual void Load (
    IDataReader^ reader, 
    LoadOption loadOption, 
    FillErrorEventHandler^ errorHandler
)
public void Load (
    IDataReader reader, 
    LoadOption loadOption, 
    FillErrorEventHandler errorHandler
)
public function Load (
    reader : IDataReader, 
    loadOption : LoadOption, 
    errorHandler : FillErrorEventHandler
)

パラメータ

reader

結果セット提供する IDataReader。

loadOption

LoadOption 列挙体の値。DataTable に既に含まれている行を同じ主キーを持つ受信した行と結合する方法示します

errorHandler

データ読み込み中にエラーが発生した場合呼び出される FillErrorEventHandler デリゲート

解説解説

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 プロパティに、イベント関連付けられている特定のアクションに関する情報格納されます。このアクション値は、読み込み操作の前の行の状態に応じて変わります。どちらの場合でも、両方イベント発生しアクション同じになります現在の行の状態に応じてアクション各行現在のバージョンまたは元のバージョン、あるいは両方バージョン適用されます。

Load メソッドLoadOption の各値を使って呼び出したときの動作次の表に示しますまた、それらの値と読み込む行の行状態との関係も示します。"(存在せず)" と表記され最後の行は、受信した行が既存の行と一致しなかった場合動作表します。この表の各マスに、行内フィールド現在の値と元の値、および Load メソッド完了した後の値の DataRowState を示します

既存の DataRowState

Upsert

OverwriteChanges

PreserveChanges (既定動作)

Added

現在の値 = <Incoming>

元の値 = -<Not available>

状態 = <Added>

RowAction = Change

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Existing>

元の値 = <Incoming>

状態 = <Modified>

RowAction = ChangeOriginal

Modified

現在の値 = <Incoming>

元の値 = <Existing>

状態 = <Modified>

RowAction = Change

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Existing>

元の値 = <Incoming>

状態 = <Modified>

RowAction = ChangeOriginal

Deleted

(削除済みの行は Load メソッド影響を受けません)

現在の値 = ---

元の値 = <Existing>

状態 = <Deleted>

(新しく追加される行は次の特性持ちます)

現在の値 = <Incoming>

元の値 = <Not available>

状態 = <Added>

RowAction = Add

削除元に戻すと、次のようになります

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Not available>

元の値 = <Incoming>

状態 = <Deleted>

RowAction = ChangeOriginal

Unchanged

現在の値 = <Incoming>

元の値 = <Existing>

新しい値が既存の値と同じ場合次のようになります

状態 = <Unchanged>

RowAction = Nothing

それ以外場合次のようになります

状態 = <Modified>

RowAction = Change

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

(存在せず)

現在の値 = <Incoming>

元の値 = <Not available>

状態 = <Added>

RowAction = Add

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

現在の値 = <Incoming>

元の値 = <Incoming>

状態 = <Unchanged>

RowAction = ChangeCurrentAndOriginal

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

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

errorHandler パラメータは、データ読み込み中にエラーが発生した場合呼び出されるプロシージャ参照する FillErrorEventHandler デリゲートです。プロシージャに FillErrorEventArgs パラメータを渡すことで得られるプロパティ使用して発生したエラーデータ現在の行、入力先の DataTable に関する情報取得できます単純な try/catch ブロック使用せず、このデリゲート機構使用することで、エラー特定状況の処理を行い、さらに必要であれば処理を続行できますFillErrorEventArgs パラメータには Continue プロパティあります。このプロパティtrue指定すると、エラーの処理後に処理を続行することが指定されます。このプロパティfalse設定すると、処理の中断指定されます。このプロパティfalse設定すると、問題の原因となったコードによって例外スローされるので注意してください

使用例使用例
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
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;
}

この例では、コンソール ウィンドウ次の出力表示します

Error when attempting to update the value: Mary
Error when attempting to update the value: Andy
Error when attempting to update the value: Peter
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

DataTable.Load メソッド

指定された IDataReader を使用し、DataTable にデータ ソースからの値を設定しますDataTable が既に行を含んでいる場合データ ソースからの受信データ既存の行にマージされます
オーバーロードの一覧オーバーロードの一覧

名前 説明
DataTable.Load (IDataReader) 指定されIDataReader使用しDataTableデータ ソースからの値を設定しますDataTable が既に行を含んでいる場合データ ソースからの受信データ既存の行にマージされます

.NET Compact Framework によってサポートされています。

DataTable.Load (IDataReader, LoadOption) 指定されIDataReader使用しDataTableデータ ソースからの値を設定しますDataTable が既に行を含んでいる場合loadOption パラメータの値に従ってデータ ソースからの受信データ既存の行にマージされます

.NET Compact Framework によってサポートされています。

DataTable.Load (IDataReader, LoadOption, FillErrorEventHandler) エラー処理デリゲート使用し指定されIDataReader使用してDataTableデータ ソースからの値を設定します

.NET Compact Framework によってサポートされています。

参照参照

関連項目

DataTable クラス
DataTable メンバ
System.Data 名前空間
Load

その他の技術情報

DataTable の作成使用
DataTable の作成使用
DataTable の作成使用 Load


このページでは「.NET Framework クラス ライブラリ リファレンス」からDataTable.Loadを検索した結果を表示しています。
Weblioに収録されているすべての辞書からDataTable.Loadを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からDataTable.Load を検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

カテゴリ一覧

すべての辞書の索引



Weblioのサービス

「DataTable.Load」の関連用語


DataTable.Loadのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



DataTable.Loadのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS