DataTable.Load 메서드

정의

제공된 DataTable를 사용해서 IDataReader을 데이터 소스의 값으로 채웁니다. DataTable에 이미 행이 포함되어 있으면 데이터 소스에서 들어오는 데이터가 기존 행과 병합됩니다.

오버로드

Load(IDataReader)

제공된 DataTable를 사용해서 IDataReader을 데이터 소스의 값으로 채웁니다. DataTable에 이미 행이 포함되어 있으면 데이터 소스에서 들어오는 데이터가 기존 행과 병합됩니다.

Load(IDataReader, LoadOption)

제공된 DataTable를 사용해서 IDataReader을 데이터 소스의 값으로 채웁니다. DataTable에 이미 행이 포함되어 있으면 데이터 소스에서 들어오는 데이터는 loadOption 매개 변수의 값에 따라 기존 행과 병합됩니다.

Load(IDataReader, LoadOption, FillErrorEventHandler)

오류 처리 대리자를 사용하는 제공된 DataTable를 사용해서 IDataReader을 데이터 소스의 값으로 채웁니다.

예제

다음 예제에서는 메서드 호출 Load 과 관련된 몇 가지 문제를 보여 줍니다. 먼저 이 예제에서는 로드된 에서 스키마를 유추한 IDataReader다음 호환되지 않는 스키마 및 누락되거나 추가 열이 있는 스키마를 처리하는 등 스키마 문제에 중점을 둡니다. 그런 다음, 이 예제에서는 다양한 로드 옵션 처리를 포함하여 데이터 문제에 중점을 둡니다.

참고

이 예제에서는 오버로드된 버전의 Load중 하나를 사용하는 방법을 보여줍니다. 사용할 수 있는 다른 예제를 오버 로드 개별 항목을 참조 하십시오.

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

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

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

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

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

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

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

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

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

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

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

    table = SetupModifiedRows();
    DisplayRowState(table);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

private static void PerformDemo(LoadOption optionForLoad)
{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  table = SetupModifiedRows()
  DisplayRowState(table)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Private Sub PerformDemo(ByVal optionForLoad As LoadOption)

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

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

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

Private Sub PrintColumns( _
   ByVal table As DataTable)

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

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

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

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

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

설명

메서드는 Load 지정된 데이터 원본에서 데이터를 가져오고 현재 데이터 컨테이너(이 경우 DataTable)에 추가하는 것을 중심으로 하는 몇 가지 일반적인 시나리오에서 사용할 수 있습니다. 이러한 시나리오에서는 업데이트 및 병합 동작을 DataTable설명하는 에 대한 표준 사용을 설명합니다.

DataTable 단일 기본 데이터 원본과 동기화하거나 업데이트합니다. 변경 DataTable 내용을 추적하여 기본 데이터 원본과의 동기화를 허용합니다. 또한 는 DataTable 하나 이상의 보조 데이터 원본에서 증분 데이터를 허용할 수 있습니다. 는 DataTable 보조 데이터 원본과의 동기화를 허용하기 위해 변경 내용을 추적할 책임이 없습니다.

이러한 두 가상 데이터 원본을 고려할 때 사용자는 다음 동작 중 하나가 필요할 수 있습니다.

  • 기본 데이터 원본에서 초기화 DataTable 합니다. 이 시나리오에서 사용자는 기본 데이터 원본의 값으로 빈 DataTable 을 초기화하려고 합니다. 나중에 사용자는 변경 내용을 기본 데이터 원본으로 다시 전파하려고 합니다.

  • 기본 데이터 원본에서 변경 내용을 보존하고 다시 동기화합니다. 이 시나리오에서 사용자는 이전 시나리오에서 채워진 를 가져와 DataTable 기본 데이터 원본과 증분 동기화를 수행하여 에서 DataTable수정한 내용을 유지하려고 합니다.

  • 보조 데이터 원본의 증분 데이터 피드입니다. 이 시나리오에서 사용자는 하나 이상의 보조 데이터 원본에서 변경 내용을 병합하고 해당 변경 내용을 기본 데이터 원본으로 다시 전파하려고 합니다.

메서드는 Load 이러한 모든 시나리오를 가능하게 합니다. 이 메서드에 대한 오버로드 중 하나를 제외한 모든 경우 이미 에 있는 행이 로드되는 행과 결합하는 방법을 나타내는 로드 옵션 매개 변수를 DataTable 지정할 수 있습니다. (동작을 지정할 수 없는 오버로드는 기본 로드 옵션을 사용합니다.) 다음 표에서는 열거형에서 제공하는 세 가지 로드 옵션에 대해 LoadOption 설명합니다. 각 경우에 설명은 들어오는 데이터에 있는 행의 기본 키가 기존 행의 기본 키와 일치하는 경우의 동작을 나타냅니다.

로드 옵션 설명
PreserveChanges(기본값) 들어오는 행의 값을 사용하여 원래 버전의 행을 업데이트.
OverwriteChanges 들어오는 행의 값을 사용하여 현재 및 원래 버전의 행을 업데이트.
Upsert 현재 버전의 행을 들어오는 행의 값으로 업데이트.

일반적으로 PreserveChanges 및 옵션은 사용자가 및 OverwriteChanges 해당 변경 내용을 기본 데이터 원본과 동기화 DataSet 해야 하는 시나리오를 위한 것입니다. 옵션은 Upsert 하나 이상의 보조 데이터 원본에서 변경 내용을 쉽게 집계할 수 있도록 합니다.

Load(IDataReader)

제공된 DataTable를 사용해서 IDataReader을 데이터 소스의 값으로 채웁니다. DataTable에 이미 행이 포함되어 있으면 데이터 소스에서 들어오는 데이터가 기존 행과 병합됩니다.

public:
 void Load(System::Data::IDataReader ^ reader);
public void Load (System.Data.IDataReader reader);
member this.Load : System.Data.IDataReader -> unit
Public Sub Load (reader As IDataReader)

매개 변수

reader
IDataReader

결과 집합을 제공하는 IDataReader입니다.

예제

다음 예제에서는 메서드 호출 Load 과 관련된 몇 가지 문제를 보여 줍니다. 먼저 이 예제에서는 로드된 에서 스키마를 유추한 IDataReader다음 호환되지 않는 스키마 및 누락되거나 추가 열이 있는 스키마를 처리하는 등 스키마 문제에 중점을 둡니다. 그런 다음, 메서드를 Load 호출하여 로드 작업 전후에 데이터를 표시합니다.

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

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

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

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

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

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

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

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

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

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

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

    table = SetupModifiedRows();
    DisplayRowState(table);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  table.Load(reader)
  PrintColumns(table)

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

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

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

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

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

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

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

  table = SetupModifiedRows()
  DisplayRowState(table)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Private Sub PrintColumns( _
   ByVal table As DataTable)

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

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

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

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

설명

메서드는 Load 로드된 의 첫 번째 결과 집합을 사용하고 성공적으로 완료된 IDataReader후 판독기 위치를 다음 결과 집합(있는 경우)으로 설정합니다. 데이터를 변환할 때 메서드는 Load 메서드와 동일한 변환 규칙을 DbDataAdapter.Fill 사용합니다.

메서드는 Load instance 데이터를 로드할 때 스키마, 데이터 IDataReader 및 이벤트 작업의 세 가지 특정 문제를 고려해야 합니다. 스키마로 작업할 때 메서드는 Load 다음 표에 설명된 대로 조건이 발생할 수 있습니다. 스키마 작업은 가져온 모든 결과 집합(데이터가 없는 결과 집합)에도 대해 수행됩니다.

조건 동작
DataTable 스키마가 없습니다. 메서드는 Load 가져온 IDataReader의 결과 집합에 따라 스키마를 유추합니다.
DataTable 스키마가 있지만 로드된 스키마와 호환되지 않습니다. 메서드는 Load 호환되지 않는 스키마에 데이터를 로드하려고 할 때 발생하는 특정 오류에 해당하는 예외를 throw합니다.
스키마는 호환되지만 로드된 결과 집합 스키마에는 에 DataTable없는 열이 포함됩니다. 메서드는 Load 의 스키마에 DataTable추가 열을 추가합니다. 및 로드된 결과 집합의 해당 열이 값과 DataTable 호환되지 않는 경우 메서드는 예외를 throw합니다. 또한 메서드는 추가된 모든 열에 대한 결과 집합에서 제약 조건 정보를 검색합니다. 기본 키 제약 조건의 경우를 제외하고 이 제약 조건 정보는 현재 DataTable 에 로드 작업 시작 시 열이 없는 경우에만 사용됩니다.
스키마는 호환되지만 로드된 결과 집합 스키마에는 보다 적은 열이 DataTable포함됩니다. 누락된 열에 기본값이 정의되어 있거나 열의 데이터 형식이 null 허용 Load 인 경우 메서드를 사용하면 누락된 열의 기본값 또는 null 값을 대체하여 행을 추가할 수 있습니다. 기본값이나 null 를 사용할 수 없는 경우 메서드는 Load 예외를 throw합니다. 특정 기본값이 제공되지 Load 않은 경우 메서드는 값을 암시적 기본값으로 사용합니다 null .

데이터 작업 측면에서 메서드의 동작을 고려하기 전에 내의 Load 각 행 DataTable 이 각 열에 대한 현재 값과 원래 값을 모두 유지하는 것을 고려합니다. 이러한 값은 동일하거나 행의 데이터가 를 채운 DataTable후 변경된 경우 다를 수 있습니다. 자세한 내용은 행 상태 및 행 버전을 참조하세요.

이 버전의 메서드는 Load 각 행의 현재 값을 유지하려고 시도하며 원래 값은 그대로 유지됩니다. (들어오는 데이터의 동작을 더 세밀하게 제어하려면 를 참조하세요 DataTable.Load.) 기존 행과 들어오는 행에 해당 기본 키 값이 포함된 경우 행은 현재 행 상태 값을 사용하여 처리되고, 그렇지 않으면 새 행으로 처리됩니다.

이벤트 작업 RowChanging 측면에서 이벤트는 각 행이 변경되기 전에 발생하며 RowChanged 각 행이 변경된 후에 이벤트가 발생합니다. 각 경우에 Action 이벤트 처리기에 전달된 instance 속성 DataRowChangeEventArgs 에는 이벤트와 연결된 특정 작업에 대한 정보가 포함됩니다. 이 작업 값은 로드 작업 전 행의 상태에 따라 달라집니다. 각 경우에 두 이벤트가 모두 발생하고 작업은 각각 동일합니다. 작업은 현재 행 상태에 따라 각 행의 현재 또는 원래 버전 또는 둘 다에 적용될 수 있습니다.

다음 표에서는 메서드에 대한 동작을 표시합니다 Load . 마지막 행("(존재하지 않음)"이라고 표시됨)은 기존 행과 일치하지 않는 들어오는 행의 동작을 설명합니다. 이 표의 각 셀은 메서드가 완료된 후 Load 의 값과 함께 행 내 필드의 현재 값과 DataRowState 원래 값을 설명합니다. 이 경우 메서드는 부하 옵션을 나타낼 수 없으며 기본값인 PreserveChanges를 사용합니다.

기존 DataRowState 메서드 뒤 Load 의 값 및 이벤트 작업
추가됨 현재 = <기존>

원본 = <수신>

상태 = <수정됨>

RowAction = ChangeOriginal
수정자 현재 = <기존>

원본 = <수신>

상태 = <수정됨>

RowAction = ChangeOriginal
삭제됨 현재 = <사용할 수 없음>

원본 = <수신>

상태 = <삭제됨>

RowAction = ChangeOriginal
변경 안 됨 현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
(존재하지 않음) 현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal

의 값은 DataColumnAutoIncrement와 같은 ReadOnly 속성을 사용하여 제한할 수 있습니다. 메서드는 Load 열의 속성에 정의된 동작과 일치하는 방식으로 이러한 열을 처리합니다. 에 대한 DataColumn 읽기 전용 제약 조건은 메모리에서 발생하는 변경 내용에만 적용됩니다. 필요한 경우 메서드는 Load 읽기 전용 열 값을 덮어씁니다.

현재 행을 들어오는 Load 행과 비교하는 데 사용할 기본 키 필드의 버전을 결정하기 위해 메서드는 행 내의 기본 키 값의 원래 버전(있는 경우)을 사용합니다. 그렇지 않으면 메서드는 Load 기본 키 필드의 현재 버전을 사용합니다.

추가 정보

적용 대상

Load(IDataReader, LoadOption)

제공된 DataTable를 사용해서 IDataReader을 데이터 소스의 값으로 채웁니다. DataTable에 이미 행이 포함되어 있으면 데이터 소스에서 들어오는 데이터는 loadOption 매개 변수의 값에 따라 기존 행과 병합됩니다.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption);
member this.Load : System.Data.IDataReader * System.Data.LoadOption -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption)

매개 변수

reader
IDataReader

하나 이상의 결과 집합을 제공하는 IDataReader입니다.

loadOption
LoadOption

LoadOption 열거형의 값으로서, 이미 DataTable에 있는 행이 동일한 기본 키를 공유하는 들어오는 행과 결합되는 방식을 나타냅니다.

예제

다음 예제에서는 메서드 호출 Load 과 관련된 몇 가지 문제를 보여 줍니다. 먼저 이 예제에서는 로드된 에서 스키마를 유추한 IDataReader다음 호환되지 않는 스키마 및 누락되거나 추가 열이 있는 스키마를 처리하는 등 스키마 문제에 중점을 둡니다. 그런 다음, 이 예제에서는 다양한 로드 옵션 처리를 포함하여 데이터 문제에 중점을 둡니다.

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

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

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

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

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

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

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

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

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

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

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

    table = SetupModifiedRows();
    DisplayRowState(table);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

private static void PerformDemo(LoadOption optionForLoad)
{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  table = SetupModifiedRows()
  DisplayRowState(table)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Private Sub PerformDemo(ByVal optionForLoad As LoadOption)

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

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

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

Private Sub PrintColumns( _
   ByVal table As DataTable)

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

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

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

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

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

설명

메서드는 Load 로드된 의 첫 번째 결과 집합을 사용하고 성공적으로 완료된 IDataReader후 판독기 위치를 다음 결과 집합(있는 경우)으로 설정합니다. 데이터를 변환할 때 메서드는 Load 메서드와 동일한 변환 규칙을 Fill 사용합니다.

메서드는 Load instance 데이터를 로드할 때 스키마, 데이터 IDataReader 및 이벤트 작업의 세 가지 특정 문제를 고려해야 합니다. 스키마로 작업할 때 메서드는 Load 다음 표에 설명된 대로 조건이 발생할 수 있습니다. 스키마 작업은 가져온 모든 결과 집합(데이터가 없는 결과 집합)에도 대해 수행됩니다.

조건 동작
DataTable 스키마가 없습니다. 메서드는 Load 가져온 IDataReader의 결과 집합에 따라 스키마를 유추합니다.
DataTable 스키마가 있지만 로드된 스키마와 호환되지 않습니다. 메서드는 Load 호환되지 않는 스키마에 데이터를 로드하려고 할 때 발생하는 특정 오류에 해당하는 예외를 throw합니다.
스키마는 호환되지만 로드된 결과 집합 스키마에는 에 DataTable없는 열이 포함됩니다. 메서드는 Load 의 스키마에 DataTable추가 열을 추가합니다. 및 로드된 결과 집합의 해당 열이 값과 DataTable 호환되지 않는 경우 메서드는 예외를 throw합니다. 또한 메서드는 추가된 모든 열에 대한 결과 집합에서 제약 조건 정보를 검색합니다. 기본 키 제약 조건의 경우를 제외하고 이 제약 조건 정보는 현재 DataTable 에 로드 작업 시작 시 열이 없는 경우에만 사용됩니다.
스키마는 호환되지만 로드된 결과 집합 스키마에는 보다 적은 열이 DataTable포함됩니다. 누락된 열에 기본값이 정의되어 있거나 열의 데이터 형식이 null 허용 Load 인 경우 메서드를 사용하면 누락된 열의 기본값 또는 null 값을 대체하여 행을 추가할 수 있습니다. 기본값 또는 null을 사용할 수 없는 경우 메서드는 Load 예외를 throw합니다. 특정 기본값이 제공되지 Load 않은 경우 메서드는 null 값을 암시적 기본값으로 사용합니다.

데이터 작업 측면에서 메서드의 동작을 고려하기 전에 내의 Load 각 행 DataTable 이 각 열에 대한 현재 값과 원래 값을 모두 유지하는 것을 고려합니다. 이러한 값은 동일하거나 행의 데이터가 를 채운 DataTable후 변경된 경우 다를 수 있습니다. 자세한 내용은 행 상태 및 행 버전을 참조하세요.

이 메서드 호출에서 지정된 LoadOption 매개 변수는 들어오는 데이터의 처리에 영향을 줍니다. Load 메서드는 기존 행과 동일한 기본 키가 있는 행 로드를 어떻게 처리해야 하나요? 현재 값, 원래 값 또는 둘 다를 수정해야 하나요? 이러한 문제 등은 매개 변수에 의해 loadOption 제어됩니다.

기존 행과 들어오는 행에 해당 기본 키 값이 포함된 경우 행은 현재 행 상태 값을 사용하여 처리되고, 그렇지 않으면 새 행으로 처리됩니다.

이벤트 작업 RowChanging 측면에서 이벤트는 각 행이 변경되기 전에 발생하며 RowChanged 각 행이 변경된 후에 이벤트가 발생합니다. 각 경우에 Action 이벤트 처리기에 전달된 instance 속성 DataRowChangeEventArgs 에는 이벤트와 연결된 특정 작업에 대한 정보가 포함됩니다. 이 작업 값은 로드 작업 전 행의 상태에 따라 달라집니다. 각 경우에 두 이벤트가 모두 발생하고 작업은 각각 동일합니다. 작업은 현재 행 상태에 따라 각 행의 현재 또는 원래 버전 또는 둘 다에 적용될 수 있습니다.

다음 표에서는 각 값과 함께 호출될 때 Load 메서드에 LoadOption 대한 동작을 표시하고 값이 로드되는 행의 행 상태와 상호 작용하는 방법도 보여 줍니다. 마지막 행("(존재하지 않음)"이라고 표시됨)은 기존 행과 일치하지 않는 들어오는 행의 동작을 설명합니다. 이 표의 각 셀은 메서드가 완료된 후 Load 의 값과 함께 행 내 필드의 현재 값과 DataRowState 원래 값을 설명합니다.

기존 DataRowState Upsert OverwriteChanges PreserveChanges(기본 동작)
추가됨 현재 = <들어오는 중>

원본 = -<사용할 수 없음>

상태 = <추가됨>

RowAction = 변경
현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <기존>

원본 = <수신>

상태 = <수정됨>

RowAction = ChangeOriginal
수정자 현재 = <들어오는 중>

원본 = <기존>

상태 = <수정됨>

RowAction = 변경
현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <기존>

원본 = <수신>

상태 = <수정됨>

RowAction =ChangeOriginal
삭제됨 (로드는 삭제된 행에 영향을 주지 않음)

Current = ---

원본 = <기존>

상태 = <삭제됨>

(다음 특성을 사용하여 새 행이 추가됨)

현재 = <들어오는 중>

원본 = <사용할 수 없음>

상태 = <추가됨>

RowAction = 추가
삭제 취소 및

현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <사용할 수 없음>

원본 = <수신>

상태 = <삭제됨>

RowAction = ChangeOriginal
변경 안 됨 현재 = <들어오는 중>

원본 = <기존>

새 값이 기존 값과 같으면

상태 = <변경되지 않음>

RowAction = Nothing

Else

상태 = <수정됨>

RowAction = 변경
현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <들어오는 중>

원본 = <들어오는 중>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
존재하지 않음) 현재 = <들어오는 중>

원본 = <사용할 수 없음>

상태 = <추가됨>

RowAction = 추가
현재 = <들어오는 중>

원본 = <들어오는 중>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <들어오는 중>

원본 = <들어오는 중>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal

의 값은 DataColumnAutoIncrement와 같은 ReadOnly 속성을 사용하여 제한될 수 있습니다. 메서드는 Load 열의 속성에 정의된 동작과 일치하는 방식으로 이러한 열을 처리합니다. 에 대한 DataColumn 읽기 전용 제약 조건은 메모리에서 발생하는 변경 내용에만 적용됩니다. Load 필요한 경우 메서드는 읽기 전용 열 값을 덮어씁니다.

메서드를 호출 Load 할 때 OverwriteChanges 또는 PreserveChanges 옵션을 지정하는 경우 들어오는 데이터가 의 기본 데이터 원본에서 DataTable들어오고 DataTable이 변경 내용을 추적하고 변경 내용을 데이터 원본으로 다시 전파할 수 있다고 가정합니다. Upsert 옵션을 선택하는 경우 데이터가 중간 계층 구성 요소에서 제공하는 데이터와 같은 보조 데이터 원본 중 하나에서 오는 것으로 가정합니다. 사용자가 변경했을 수 있습니다. 이 경우 의 하나 이상의 데이터 원본에서 데이터를 집계한 다음 데이터를 기본 데이터 원본 DataTable으로 다시 전파하려는 의도가 있다고 가정합니다. LoadOption 매개 변수는 기본 키 비교에 사용할 행의 특정 버전을 결정하는 데 사용됩니다. 아래 표에서는 세부 정보를 제공합니다.

로드 옵션 기본 키 비교에 사용되는 DataRow 버전
OverwriteChanges 원래 버전(있는 경우)이고, 그렇지 않으면 현재 버전입니다.
PreserveChanges 원래 버전(있는 경우)이고, 그렇지 않으면 현재 버전입니다.
Upsert 현재 버전(있는 경우)이고, 그렇지 않으면 원래 버전입니다.

추가 정보

적용 대상

Load(IDataReader, LoadOption, FillErrorEventHandler)

오류 처리 대리자를 사용하는 제공된 DataTable를 사용해서 IDataReader을 데이터 소스의 값으로 채웁니다.

public:
 virtual void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, System::Data::FillErrorEventHandler ^ errorHandler);
public virtual void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler? errorHandler);
public virtual void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler);
abstract member Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
Public Overridable Sub Load (reader As IDataReader, loadOption As LoadOption, errorHandler As FillErrorEventHandler)

매개 변수

reader
IDataReader

결과 집합을 제공하는 IDataReader입니다.

loadOption
LoadOption

LoadOption 열거형의 값으로서, 이미 DataTable에 있는 행이 동일한 기본 키를 공유하는 들어오는 행과 결합되는 방식을 나타냅니다.

errorHandler
FillErrorEventHandler

데이터를 로드하는 동안 오류가 발생하면 호출할 FillErrorEventHandler 대리자입니다.

예제

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Private Sub PrintColumns( _
   ByVal table As DataTable)

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

설명

메서드는 Load 로드된 의 첫 번째 결과 집합을 사용하고 성공적으로 완료된 IDataReader후 판독기 위치를 다음 결과 집합(있는 경우)으로 설정합니다. 데이터를 변환할 때 메서드는 Load 메서드와 동일한 변환 규칙을 DbDataAdapter.Fill 사용합니다.

메서드는 Load instance 데이터를 로드할 때 스키마, 데이터 IDataReader 및 이벤트 작업의 세 가지 특정 문제를 고려해야 합니다. 스키마를 사용할 때 메서드는 Load 다음 표에 설명된 대로 조건이 발생할 수 있습니다. 스키마 작업은 데이터를 포함하지 않는 결과 집합을 비롯하여 가져온 모든 결과 집합에 대해 수행됩니다.

조건 동작
DataTable 스키마가 없습니다. 메서드는 Load 가져온 IDataReader의 결과 집합에 따라 스키마를 유추합니다.
DataTable 스키마가 있지만 로드된 스키마와 호환되지 않습니다. 메서드는 Load 호환되지 않는 스키마에 데이터를 로드하려고 할 때 발생하는 특정 오류에 해당하는 예외를 throw합니다.
스키마는 호환되지만 로드된 결과 집합 스키마에는 에 DataTable없는 열이 포함됩니다. 메서드는 Load 의 스키마에 DataTable추가 열을 추가합니다. 및 로드된 결과 집합의 DataTable 해당 열이 값과 호환되지 않는 경우 메서드는 예외를 throw합니다. 또한 메서드는 추가된 모든 열에 대한 결과 집합에서 제약 조건 정보를 검색합니다. 기본 키 제약 조건의 경우를 제외하고 이 제약 조건 정보는 현재 DataTable 에 로드 작업 시작 시 열이 없는 경우에만 사용됩니다.
스키마는 호환되지만 로드된 결과 집합 스키마에는 보다 적은 수의 열이 DataTable포함됩니다. 누락된 열에 기본값이 정의되어 있거나 열의 데이터 형식이 null 허용 Load 인 경우 메서드를 사용하면 행을 추가할 수 있으며 누락된 열의 기본값 또는 null 값을 대체합니다. 기본값 또는 null을 사용할 수 없는 경우 메서드는 Load 예외를 throw합니다. 특정 기본값이 제공되지 Load 않은 경우 메서드는 null 값을 암시적 기본값으로 사용합니다.

데이터 작업 측면에서 메서드의 Load 동작을 고려하기 전에 내의 각 행 DataTable 이 각 열에 대한 현재 값과 원래 값을 모두 유지 관리하는 것을 고려합니다. 이러한 값은 을 채운 DataTable후 행의 데이터가 변경된 경우 동일하거나 다를 수 있습니다. 자세한 내용은 행 상태 및 행 버전을 참조하세요.

이 메서드 호출에서 지정된 LoadOption 매개 변수는 들어오는 데이터의 처리에 영향을 줍니다. Load 메서드는 기존 행과 동일한 기본 키가 있는 행 로드를 어떻게 처리해야 하나요? 현재 값, 원래 값 또는 둘 다를 수정해야 하나요? 이러한 문제 등은 매개 변수에 의해 loadOption 제어됩니다.

기존 행과 들어오는 행에 해당 기본 키 값이 포함된 경우 행은 현재 행 상태 값을 사용하여 처리되고, 그렇지 않으면 새 행으로 처리됩니다.

이벤트 작업 RowChanging 측면에서 이벤트는 각 행이 변경되기 전에 발생하며 RowChanged 각 행이 변경된 후에 이벤트가 발생합니다. 각각의 경우 이벤트 Action 처리기에 전달된 instance 속성 DataRowChangeEventArgs 에는 이벤트와 연결된 특정 작업에 대한 정보가 포함됩니다. 이 작업 값은 로드 작업 전 행의 상태에 따라 달라집니다. 각 경우에 두 이벤트가 모두 발생하고 작업은 각각에 대해 동일합니다. 작업은 현재 행 상태에 따라 각 행의 현재 또는 원래 버전 또는 둘 다에 적용될 수 있습니다.

다음 표에서는 각 값과 함께 호출될 때 Load 메서드에 LoadOption 대한 동작을 표시하고 값이 로드되는 행의 행 상태와 상호 작용하는 방법도 보여 줍니다. 마지막 행("(존재하지 않음)"이라고 표시됨)은 기존 행과 일치하지 않는 들어오는 행의 동작을 설명합니다. 이 표의 각 셀은 메서드가 완료된 후의 값에 대한 와 함께 행 내 필드의 Load 현재 값과 DataRowState 원래 값을 설명합니다.

기존 DataRowState Upsert OverwriteChanges PreserveChanges(기본 동작)
추가됨 현재 = <들어오는 중>

원본 = -<사용할 수 없음>

상태 = <추가됨>

RowAction = 변경
현재 = <들어오는 중>

원본 = <들어오는 중>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <기존>

원본 = <들어오는 중>

상태 = <수정됨>

RowAction = ChangeOriginal
수정자 현재 = <들어오는 중>

원본 = <기존>

상태 = <수정됨>

RowAction = 변경
현재 = <들어오는 중>

원본 = <들어오는 중>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <기존>

원본 = <수신>

상태 = <수정됨>

RowAction =ChangeOriginal
eleted (로드는 삭제된 행에 영향을 주지 않음)

Current = ---

원본 = <기존>

상태 = <삭제됨>

(다음 특성을 사용하여 새 행이 추가됨)

현재 = <들어오는 중>

원본 = <사용할 수 없음>

상태 = <추가됨>

RowAction = 추가
삭제 취소 및

현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <사용할 수 없음>

원본 = <수신>

상태 = <삭제됨>

RowAction = ChangeOriginal
변경 안 됨 현재 = <들어오는 중>

원본 = <기존>

새 값이 기존 값과 같으면

상태 = <변경되지 않음>

RowAction = Nothing

Else

상태 = <수정됨>

RowAction = 변경
현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
존재하지 않음) 현재 = <들어오는 중>

원본 = <사용할 수 없음>

상태 = <추가됨>

RowAction = 추가
현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal
현재 = <들어오는 중>

원본 = <수신>

상태 = <변경되지 않음>

RowAction = ChangeCurrentAndOriginal

의 값은 DataColumnAutoIncrement와 같은 ReadOnly 속성을 사용하여 제한할 수 있습니다. 메서드는 Load 열의 속성에 정의된 동작과 일치하는 방식으로 이러한 열을 처리합니다. 에 대한 DataColumn 읽기 전용 제약 조건은 메모리에서 발생하는 변경 내용에만 적용됩니다. 필요한 경우 메서드는 Load 읽기 전용 열 값을 덮어씁니다.

메서드를 호출 Load 할 때 OverwriteChanges 또는 PreserveChanges 옵션을 지정하는 경우 들어오는 데이터가 의 기본 데이터 원본에서 DataTable들어오고 DataTable이 변경 내용을 추적하고 변경 내용을 데이터 원본으로 다시 전파할 수 있다고 가정합니다. Upsert 옵션을 선택하는 경우 데이터가 중간 계층 구성 요소에서 제공하는 데이터와 같은 보조 데이터 원본 중 하나에서 오는 것으로 가정합니다( 아마도 사용자가 변경한 데이터). 이 경우 의 하나 이상의 데이터 원본에서 데이터를 집계한 다음, 데이터를 기본 데이터 원본 DataTable으로 다시 전파하려는 의도가 있다고 가정합니다. LoadOption 매개 변수는 기본 키 비교에 사용할 행의 특정 버전을 결정하는 데 사용됩니다. 아래 표에서는 세부 정보를 제공합니다.

로드 옵션 기본 키 비교에 사용되는 DataRow 버전
OverwriteChanges 원래 버전이 있는 경우 현재 버전이 아닌 경우
PreserveChanges 원래 버전이 있는 경우 현재 버전이 아닌 경우
Upsert 현재 버전이 있는 경우 원래 버전이 아닌 경우

errorHandler 매개 변수는 FillErrorEventHandler 데이터를 로드하는 동안 오류가 발생할 때 호출되는 프로시저를 참조하는 대리자입니다. 프로시저에 전달된 매개 변수는 FillErrorEventArgs 발생한 오류, 현재 데이터 행 및 DataTable 채워지는 에 대한 정보를 검색할 수 있는 속성을 제공합니다. 더 간단한 try/catch 블록이 아닌 이 대리자 메커니즘을 사용하면 오류를 확인하고, 상황을 처리하고, 원하는 경우 처리를 계속할 수 있습니다. 매개 변수는 FillErrorEventArgs 속성을 제공합니다 Continue . 이 속성을 true 로 설정하여 오류를 처리했으며 처리를 계속하려고 함을 나타냅니다. 처리를 중지할 것임을 나타내려면 속성을 false 로 설정합니다. 속성을 false 로 설정하면 문제를 트리거한 코드가 예외를 throw합니다.

추가 정보

적용 대상