Udostępnij za pośrednictwem


DataTable.Load Metoda

Definicja

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . Jeśli obiekt DataTable zawiera już wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami.

Przeciążenia

Nazwa Opis
Load(IDataReader)

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . Jeśli obiekt DataTable zawiera już wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami.

Load(IDataReader, LoadOption)

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . DataTable Jeśli obiekt zawiera już wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami zgodnie z wartością parametruloadOption.

Load(IDataReader, LoadOption, FillErrorEventHandler)

Wypełnia element DataTable wartościami ze źródła danych przy użyciu dostarczonego IDataReader delegata obsługi błędów.

Przykłady

W poniższym przykładzie pokazano kilka problemów związanych z wywoływaniem Load metody . Najpierw przykład koncentruje się na problemach ze schematem, w tym wnioskowaniu schematu z załadowanych IDataReaderschematów, a następnie obsłudze niezgodnych schematów i schematów z brakującymi lub dodatkowymi kolumnami. W tym przykładzie skupiono się na problemach z danymi, w tym na obsłudze różnych opcji ładowania.

Uwaga / Notatka

W tym przykładzie pokazano, jak używać jednej z przeciążonych wersji programu Load. Aby zapoznać się z innymi przykładami, które mogą być dostępne, zobacz poszczególne tematy przeciążenia.

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

Uwagi

Metodę Load można użyć w kilku typowych scenariuszach, wszystkie skupione wokół pobierania danych z określonego źródła danych i dodawania ich do bieżącego kontenera danych (w tym przypadku ).DataTable W tych scenariuszach opisano standardowe użycie elementu DataTable, opisując jego działanie aktualizacji i scalania.

Synchronizacja DataTable lub aktualizacje z jednym podstawowym źródłem danych. Śledzi DataTable zmiany, umożliwiając synchronizację z podstawowym źródłem danych. Ponadto obiekt DataTable może akceptować dane przyrostowe z co najmniej jednego pomocniczego źródła danych. Element DataTable nie jest odpowiedzialny za śledzenie zmian w celu umożliwienia synchronizacji z pomocniczym źródłem danych.

Biorąc pod uwagę te dwa hipotetyczne źródła danych, użytkownik może wymagać jednego z następujących zachowań:

  • Zainicjuj DataTable z podstawowego źródła danych. W tym scenariuszu użytkownik chce zainicjować pusty DataTable element z wartościami z podstawowego źródła danych. Później użytkownik zamierza propagować zmiany z powrotem do podstawowego źródła danych.

  • Zachowaj zmiany i ponownie zsynchronizuj je z podstawowego źródła danych. W tym scenariuszu użytkownik chce wykonać DataTable wypełnioną w poprzednim scenariuszu synchronizację przyrostową z podstawowym źródłem danych, zachowując modyfikacje wprowadzone w pliku DataTable.

  • Przyrostowe źródło danych z pomocniczych źródeł danych. W tym scenariuszu użytkownik chce scalić zmiany z co najmniej jednego pomocniczego źródła danych i propagować te zmiany z powrotem do podstawowego źródła danych.

Metoda Load umożliwia wykonanie wszystkich tych scenariuszy. Wszystkie, ale jedno z przeciążeń dla tej metody umożliwia określenie parametru opcji ładowania, wskazując, jak wiersze już w DataTable połączeniu z ładowanymi wierszami. (Przeciążenie, które nie zezwala na określenie zachowania, używa domyślnej opcji ładowania). W poniższej LoadOption tabeli opisano trzy opcje ładowania udostępniane przez wyliczenie. W każdym przypadku opis wskazuje zachowanie, gdy klucz podstawowy wiersza w danych przychodzących jest zgodny z kluczem podstawowym istniejącego wiersza.

Opcja ładowania Opis
PreserveChanges (ustawienie domyślne) Aktualizuje oryginalną wersję wiersza wartością wiersza przychodzącego.
OverwriteChanges Aktualizuje bieżące i oryginalne wersje wiersza z wartością wiersza przychodzącego.
Upsert Aktualizuje bieżącą wersję wiersza z wartością wiersza przychodzącego.

Ogólnie rzecz biorąc, opcje i OverwriteChanges są przeznaczone dla scenariuszy, PreserveChanges w których użytkownik musi zsynchronizować DataSet zmiany i z podstawowym źródłem danych. Opcja Upsert ułatwia agregowanie zmian z co najmniej jednego pomocniczego źródła danych.

Load(IDataReader)

Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . Jeśli obiekt DataTable zawiera już wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami.

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

Parametry

reader
IDataReader

Element IDataReader , który udostępnia zestaw wyników.

Atrybuty

Przykłady

W poniższym przykładzie pokazano kilka problemów związanych z wywoływaniem Load metody . Najpierw przykład koncentruje się na problemach ze schematem, w tym wnioskowaniu schematu z załadowanych IDataReaderschematów, a następnie obsłudze niezgodnych schematów i schematów z brakującymi lub dodatkowymi kolumnami. Następnie przykład wywołuje metodę Load , wyświetlając dane zarówno przed, jak i po operacji ładowania.

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

Uwagi

Metoda Load używa pierwszego zestawu wyników z załadowanego IDataReaderzestawu wyników, a po pomyślnym zakończeniu ustawia pozycję czytelnika na następny zestaw wyników, jeśli istnieje. Podczas konwertowania danych Load metoda używa tych samych reguł konwersji co DbDataAdapter.Fill metoda.

Metoda Load musi uwzględniać trzy konkretne problemy podczas ładowania danych z IDataReader wystąpienia: schematu, danych i operacji zdarzeń. Podczas pracy ze schematem Load metoda może napotkać warunki zgodnie z opisem w poniższej tabeli. Operacje schematu są wykonywane dla wszystkich zaimportowanych zestawów wyników, nawet tych, które nie zawierają żadnych danych.

Warunek Zachowanie
Element DataTable nie ma schematu. Metoda Load wywnioskuje schemat na podstawie zestawu wyników z zaimportowanego IDataReaderelementu .
Element DataTable ma schemat, ale jest niezgodny z załadowanym schematem. Metoda Load zgłasza wyjątek odpowiadający konkretnemu błędowi, który występuje podczas próby załadowania danych do niezgodnego schematu.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera kolumny, które nie istnieją w obiekcie DataTable. Metoda Load dodaje dodatkowe kolumny do DataTableschematu . Metoda zgłasza wyjątek, jeśli odpowiednie kolumny w DataTable zestawie wyników i załadowany zestaw wyników nie są zgodne z wartością. Metoda pobiera również informacje o ograniczeniu z zestawu wyników dla wszystkich dodanych kolumn. Z wyjątkiem ograniczenia klucza podstawowego, te informacje ograniczenia są używane tylko wtedy, gdy bieżący DataTable nie zawiera żadnych kolumn na początku operacji ładowania.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera mniej kolumn niż .DataTable Jeśli brakująca kolumna ma zdefiniowaną wartość domyślną lub typ danych kolumny ma wartość null, Load metoda umożliwia dodanie wierszy, zastąpienie wartości domyślnej lub null wartości brakującej kolumny. Jeśli nie ma wartości domyślnej lub null można jej użyć, Load metoda zgłasza wyjątek. Jeśli nie podano określonej wartości domyślnej, Load metoda używa null wartości jako sugerowanej wartości domyślnej.

Przed rozważeniem zachowania Load metody w zakresie operacji danych należy wziąć pod uwagę, że każdy wiersz w obiekcie DataTable zachowuje zarówno bieżącą wartość, jak i oryginalną wartość dla każdej kolumny. Te wartości mogą być równoważne lub mogą być inne, jeśli dane w wierszu zostały zmienione od czasu wypełnienia .DataTable Aby uzyskać więcej informacji, zobacz Row States and Row Versions (Stany wierszy i wersje wierszy).

Ta wersja Load metody próbuje zachować bieżące wartości w każdym wierszu, pozostawiając oryginalną wartość bez zmian. (Jeśli chcesz uzyskać dokładną kontrolę nad zachowaniem danych przychodzących, zobacz DataTable.Load. Jeśli istniejący wiersz i wiersz przychodzący zawierają odpowiednie wartości klucza podstawowego, wiersz jest przetwarzany przy użyciu bieżącej wartości stanu wiersza, w przeciwnym razie jest traktowany jako nowy wiersz.

Jeśli chodzi o operacje zdarzeń, RowChanging zdarzenie występuje przed zmianą każdego wiersza, a RowChanged zdarzenie występuje po zmianie każdego wiersza. W każdym przypadku Action właściwość wystąpienia przekazanego DataRowChangeEventArgs do programu obsługi zdarzeń zawiera informacje o określonej akcji skojarzonej ze zdarzeniem. Ta wartość akcji zależy od stanu wiersza przed operacją ładowania. W każdym przypadku występują oba zdarzenia, a akcja jest taka sama dla każdego z nich. Akcja może być stosowana do bieżącej lub oryginalnej wersji każdego wiersza albo obu tych elementów w zależności od bieżącego stanu wiersza.

W poniższej Load tabeli przedstawiono zachowanie metody . Ostatni wiersz (oznaczony etykietą "(Nie ma)") opisuje zachowanie dla wierszy przychodzących, które nie pasują do żadnego istniejącego wiersza. Każda komórka w tej tabeli opisuje bieżącą i oryginalną wartość pola w wierszu wraz z DataRowState wartością dla wartości po zakończeniu Load metody. W takim przypadku metoda nie zezwala na wskazanie opcji ładowania i używa wartości domyślnej PreserveChanges.

Istniejąca dataRowState Wartości po Load metodzie i akcji zdarzenia
Dodano Current = <Istniejący>

Oryginalny = <przychodzący>

State = Modified (Stan = <Zmodyfikowany)>

RowAction = ChangeOriginal
Zmodyfikowano Current = <Istniejący>

Oryginalny = <przychodzący>

State = Modified (Stan = <Zmodyfikowany)>

RowAction = ChangeOriginal
Usunięto Current = <niedostępny>

Oryginalny = <przychodzący>

State = Deleted (Stan = <Usunięto)>

RowAction = ChangeOriginal
Niezmienione Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
(Nie ma) Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal

Wartości w obiekcie DataColumn można ograniczyć za pomocą właściwości, takich jak ReadOnly i AutoIncrement. Metoda Load obsługuje takie kolumny w sposób zgodny z zachowaniem zdefiniowanym przez właściwości kolumny. Ograniczenie tylko do odczytu dla elementu DataColumn ma zastosowanie tylko w przypadku zmian występujących w pamięci. W Load razie potrzeby metoda zastępuje wartości kolumn tylko do odczytu.

Aby określić, która wersja pola klucza podstawowego ma być używana do porównywania bieżącego wiersza z wierszem przychodzącym, Load metoda używa oryginalnej wersji wartości klucza podstawowego w wierszu, jeśli istnieje. Load W przeciwnym razie metoda używa bieżącej wersji pola klucza podstawowego.

Zobacz też

Dotyczy

Load(IDataReader, LoadOption)

Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . DataTable Jeśli obiekt zawiera już wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami zgodnie z wartością parametruloadOption.

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

Parametry

reader
IDataReader

Element IDataReader , który udostępnia co najmniej jeden zestaw wyników.

loadOption
LoadOption

Wartość z LoadOption wyliczenia, która wskazuje, w jaki sposób wiersze już w obiekcie DataTable są łączone z wierszami przychodzącymi, które współużytkują ten sam klucz podstawowy.

Atrybuty

Przykłady

W poniższym przykładzie pokazano kilka problemów związanych z wywoływaniem Load metody . Najpierw przykład koncentruje się na problemach ze schematem, w tym wnioskowaniu schematu z załadowanych IDataReaderschematów, a następnie obsłudze niezgodnych schematów i schematów z brakującymi lub dodatkowymi kolumnami. W tym przykładzie skupiono się na problemach z danymi, w tym na obsłudze różnych opcji ładowania.

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

Uwagi

Metoda Load używa pierwszego zestawu wyników z załadowanego IDataReaderzestawu wyników, a po pomyślnym zakończeniu ustawia pozycję czytelnika na następny zestaw wyników, jeśli istnieje. Podczas konwertowania danych Load metoda używa tych samych reguł konwersji co Fill metoda.

Metoda Load musi uwzględniać trzy konkretne problemy podczas ładowania danych z IDataReader wystąpienia: schematu, danych i operacji zdarzeń. Podczas pracy ze schematem Load metoda może napotkać warunki zgodnie z opisem w poniższej tabeli. Operacje schematu są wykonywane dla wszystkich zaimportowanych zestawów wyników, nawet tych, które nie zawierają żadnych danych.

Warunek Zachowanie
Element DataTable nie ma schematu. Metoda Load wywnioskuje schemat na podstawie zestawu wyników z zaimportowanego IDataReaderelementu .
Element DataTable ma schemat, ale jest niezgodny z załadowanym schematem. Metoda Load zgłasza wyjątek odpowiadający konkretnemu błędowi, który występuje podczas próby załadowania danych do niezgodnego schematu.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera kolumny, które nie istnieją w obiekcie DataTable. Metoda Load dodaje dodatkowe kolumny do DataTableschematu . Metoda zgłasza wyjątek, jeśli odpowiednie kolumny w DataTable zestawie wyników i załadowany zestaw wyników nie są zgodne z wartością. Metoda pobiera również informacje o ograniczeniu z zestawu wyników dla wszystkich dodanych kolumn. Z wyjątkiem ograniczenia klucza podstawowego, te informacje ograniczenia są używane tylko wtedy, gdy bieżący DataTable nie zawiera żadnych kolumn na początku operacji ładowania.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera mniej kolumn niż .DataTable Jeśli brakująca kolumna ma zdefiniowaną wartość domyślną lub typ danych kolumny ma wartość null, Load metoda umożliwia dodanie wierszy, zastąpienie wartości domyślnej lub null brakującej kolumny. Jeśli nie można użyć wartości domyślnej lub wartości null, Load metoda zgłasza wyjątek. Jeśli nie podano określonej wartości domyślnej, Load metoda używa wartości null jako sugerowanej wartości domyślnej.

Przed rozważeniem zachowania Load metody w zakresie operacji danych należy wziąć pod uwagę, że każdy wiersz w obiekcie DataTable zachowuje zarówno bieżącą wartość, jak i oryginalną wartość dla każdej kolumny. Te wartości mogą być równoważne lub mogą być inne, jeśli dane w wierszu zostały zmienione od czasu wypełnienia .DataTable Aby uzyskać więcej informacji, zobacz Stany wierszy i wersje wierszy .

W tym wywołaniu metody określony LoadOption parametr wpływa na przetwarzanie danych przychodzących. Jak metoda Load powinna obsługiwać ładowanie wierszy, które mają ten sam klucz podstawowy co istniejące wiersze? Czy należy zmodyfikować bieżące wartości, oryginalne wartości lub oba te wartości? Te problemy i nie tylko są kontrolowane przez loadOption parametr .

Jeśli istniejący wiersz i wiersz przychodzący zawierają odpowiednie wartości klucza podstawowego, wiersz jest przetwarzany przy użyciu bieżącej wartości stanu wiersza, w przeciwnym razie jest traktowany jako nowy wiersz.

Jeśli chodzi o operacje zdarzeń, RowChanging zdarzenie występuje przed zmianą każdego wiersza, a RowChanged zdarzenie występuje po zmianie każdego wiersza. W każdym przypadku Action właściwość wystąpienia przekazanego DataRowChangeEventArgs do programu obsługi zdarzeń zawiera informacje o określonej akcji skojarzonej ze zdarzeniem. Ta wartość akcji różni się w zależności od stanu wiersza przed operacją ładowania. W każdym przypadku występują oba zdarzenia, a akcja jest taka sama dla każdego z nich. Akcja może być stosowana do bieżącej lub oryginalnej wersji każdego wiersza albo obu tych elementów w zależności od bieżącego stanu wiersza.

W poniższej tabeli przedstawiono zachowanie metody Load po wywołaniu z każdą LoadOption z wartości, a także pokazano, jak wartości wchodzą w interakcję ze stanem wiersza dla ładowanego wiersza. Ostatni wiersz (oznaczony etykietą "(Nie ma)") opisuje zachowanie dla wierszy przychodzących, które nie pasują do żadnego istniejącego wiersza. Każda komórka w tej tabeli opisuje bieżącą i oryginalną wartość pola w wierszu wraz z DataRowState wartością dla wartości po zakończeniu Load metody.

Istniejąca dataRowState Upsert Overwritechanges PreserveChanges (zachowanie domyślne)
Dodano Current = <Przychodzące>

Oryginalny = -<Niedostępny>

Stan = <Dodano>

RowAction = Change
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <Istniejący>

Oryginalny = <przychodzący>

State = Modified (Stan = <Zmodyfikowany)>

RowAction = ChangeOriginal
Zmodyfikowano Current = <Przychodzące>

Oryginalny = <istniejący>

State = Modified (Stan = <Zmodyfikowany)>

RowAction = Change
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <Istniejący>

Oryginalny = <przychodzący>

State = Modified (Stan = <Zmodyfikowany)>

RowAction =ChangeOriginal
Usunięto (Ładowanie nie ma wpływu na usunięte wiersze)

Current = ---

Oryginalny = <istniejący>

State = Deleted (Stan = <Usunięto)>

(Nowy wiersz jest dodawany z następującymi cechami)

Current = <Przychodzące>

Oryginalny = <niedostępny>

Stan = <Dodano>

RowAction = Add
Cofnij usuwanie i

Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <niedostępny>

Oryginalny = <przychodzący>

State = Deleted (Stan = <Usunięto)>

RowAction = ChangeOriginal
Niezmienione Current = <Przychodzące>

Oryginalny = <istniejący>

Jeśli nowa wartość jest taka sama jak istniejąca wartość, wówczas

Stan = <niezmienione>

RowAction = nic

Innego

State = Modified (Stan = <Zmodyfikowany)>

RowAction = Change
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Nie ma) Current = <Przychodzące>

Oryginalny = <niedostępny>

Stan = <Dodano>

RowAction = Add
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal

Wartości w obiekcie DataColumn można ograniczyć za pomocą właściwości, takich jak ReadOnly i AutoIncrement. Metoda Load obsługuje takie kolumny w sposób zgodny z zachowaniem zdefiniowanym przez właściwości kolumny. Ograniczenie tylko do odczytu dla elementu DataColumn ma zastosowanie tylko w przypadku zmian występujących w pamięci. W Load razie potrzeby metoda zastępuje wartości kolumn tylko do odczytu.

Jeśli podczas wywoływania Load metody określisz opcje OverwriteChanges lub PreserveChanges, zakłada się, że dane przychodzące pochodzą z podstawowego DataTableźródła danych, a tabela DataTable śledzi zmiany i może propagować zmiany z powrotem do źródła danych. W przypadku wybrania opcji Upsert zakłada się, że dane pochodzą z jednego z pomocniczych źródeł danych, takich jak dane dostarczane przez składnik warstwy środkowej, być może zmienione przez użytkownika. W takim przypadku założeniem jest to, że celem jest agregowanie danych z co najmniej jednego źródła danych w DataTableobiekcie , a następnie propagowanie danych z powrotem do podstawowego źródła danych. Parametr LoadOption służy do określania konkretnej wersji wiersza, który ma być używany do porównania klucza podstawowego. Poniższa tabela zawiera szczegółowe informacje.

Opcja ładowania Wersja elementu DataRow używana na potrzeby porównania klucza podstawowego
OverwriteChanges Oryginalna wersja, jeśli istnieje, w przeciwnym razie bieżąca wersja
PreserveChanges Oryginalna wersja, jeśli istnieje, w przeciwnym razie bieżąca wersja
Upsert Bieżąca wersja, jeśli istnieje, w przeciwnym razie oryginalna wersja

Zobacz też

Dotyczy

Load(IDataReader, LoadOption, FillErrorEventHandler)

Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs

Wypełnia element DataTable wartościami ze źródła danych przy użyciu dostarczonego IDataReader delegata obsługi błędów.

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

Parametry

reader
IDataReader

Element IDataReader , który udostępnia zestaw wyników.

loadOption
LoadOption

Wartość z LoadOption wyliczenia, która wskazuje, w jaki sposób wiersze już w obiekcie DataTable są łączone z wierszami przychodzącymi, które współużytkują ten sam klucz podstawowy.

errorHandler
FillErrorEventHandler

Delegat FillErrorEventHandler do wywołania w przypadku wystąpienia błędu podczas ładowania danych.

Atrybuty

Przykłady

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

Uwagi

Metoda Load używa pierwszego zestawu wyników z załadowanego IDataReaderzestawu wyników, a po pomyślnym zakończeniu ustawia pozycję czytelnika na następny zestaw wyników, jeśli istnieje. Podczas konwertowania danych Load metoda używa tych samych reguł konwersji co DbDataAdapter.Fill metoda.

Metoda Load musi uwzględniać trzy konkretne problemy podczas ładowania danych z IDataReader wystąpienia: schematu, danych i operacji zdarzeń. Podczas pracy ze schematem Load metoda może napotkać warunki zgodnie z opisem w poniższej tabeli. Operacje schematu są wykonywane dla wszystkich zaimportowanych zestawów wyników, nawet tych, które nie zawierają żadnych danych.

Warunek Zachowanie
Element DataTable nie ma schematu. Metoda Load wywnioskuje schemat na podstawie zestawu wyników z zaimportowanego IDataReaderelementu .
Element DataTable ma schemat, ale jest niezgodny z załadowanym schematem. Metoda Load zgłasza wyjątek odpowiadający konkretnemu błędowi, który występuje podczas próby załadowania danych do niezgodnego schematu.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera kolumny, które nie istnieją w obiekcie DataTable. Metoda Load dodaje dodatkowe kolumny do DataTableschematu . Metoda zgłasza wyjątek, jeśli odpowiednie kolumny w DataTable zestawie wyników i załadowany zestaw wyników nie są zgodne z wartością. Metoda pobiera również informacje o ograniczeniu z zestawu wyników dla wszystkich dodanych kolumn. Z wyjątkiem ograniczenia klucza podstawowego, te informacje ograniczenia są używane tylko wtedy, gdy bieżący DataTable nie zawiera żadnych kolumn na początku operacji ładowania.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera mniej kolumn niż .DataTable Jeśli brakująca kolumna ma zdefiniowaną wartość domyślną lub typ danych kolumny ma wartość null, Load metoda umożliwia dodanie wierszy, zastąpienie wartości domyślnej lub null brakującej kolumny. Jeśli nie można użyć wartości domyślnej lub wartości null, Load metoda zgłasza wyjątek. Jeśli nie podano określonej wartości domyślnej, Load metoda używa wartości null jako sugerowanej wartości domyślnej.

Przed rozważeniem zachowania Load metody w zakresie operacji danych należy wziąć pod uwagę, że każdy wiersz w obiekcie DataTable zachowuje zarówno bieżącą wartość, jak i oryginalną wartość dla każdej kolumny. Te wartości mogą być równoważne lub mogą być inne, jeśli dane w wierszu zostały zmienione od czasu wypełnienia .DataTable Aby uzyskać więcej informacji, zobacz Stany wierszy i wersje wierszy .

W tym wywołaniu metody określony LoadOption parametr wpływa na przetwarzanie danych przychodzących. Jak metoda Load powinna obsługiwać ładowanie wierszy, które mają ten sam klucz podstawowy co istniejące wiersze? Czy należy zmodyfikować bieżące wartości, oryginalne wartości lub oba te wartości? Te problemy i nie tylko są kontrolowane przez loadOption parametr .

Jeśli istniejący wiersz i wiersz przychodzący zawierają odpowiednie wartości klucza podstawowego, wiersz jest przetwarzany przy użyciu bieżącej wartości stanu wiersza, w przeciwnym razie jest traktowany jako nowy wiersz.

Jeśli chodzi o operacje zdarzeń, RowChanging zdarzenie występuje przed zmianą każdego wiersza, a RowChanged zdarzenie występuje po zmianie każdego wiersza. W każdym przypadku Action właściwość wystąpienia przekazanego DataRowChangeEventArgs do programu obsługi zdarzeń zawiera informacje o określonej akcji skojarzonej ze zdarzeniem. Ta wartość akcji różni się w zależności od stanu wiersza przed operacją ładowania. W każdym przypadku występują oba zdarzenia, a akcja jest taka sama dla każdego z nich. Akcja może być stosowana do bieżącej lub oryginalnej wersji każdego wiersza albo obu tych elementów w zależności od bieżącego stanu wiersza.

W poniższej tabeli przedstawiono zachowanie metody Load po wywołaniu z każdą LoadOption z wartości, a także pokazano, jak wartości wchodzą w interakcję ze stanem wiersza dla ładowanego wiersza. Ostatni wiersz (oznaczony etykietą "(Nie ma)") opisuje zachowanie dla wierszy przychodzących, które nie pasują do żadnego istniejącego wiersza. Każda komórka w tej tabeli opisuje bieżącą i oryginalną wartość pola w wierszu wraz z DataRowState wartością dla wartości po zakończeniu Load metody.

Istniejąca dataRowState Upsert Overwritechanges PreserveChanges (zachowanie domyślne)
Dodano Current = <Przychodzące>

Oryginalny = -<Niedostępny>

Stan = <Dodano>

RowAction = Change
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <Istniejący>

Oryginalny = <przychodzący>

State = Modified (Stan = <Zmodyfikowany)>

RowAction = ChangeOriginal
Zmodyfikowano Current = <Przychodzące>

Oryginalny = <istniejący>

State = Modified (Stan = <Zmodyfikowany)>

RowAction = Change
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <Istniejący>

Oryginalny = <przychodzący>

State = Modified (Stan = <Zmodyfikowany)>

RowAction =ChangeOriginal
eletowane (Ładowanie nie ma wpływu na usunięte wiersze)

Current = ---

Oryginalny = <istniejący>

State = Deleted (Stan = <Usunięto)>

(Nowy wiersz jest dodawany z następującymi cechami)

Current = <Przychodzące>

Oryginalny = <niedostępny>

Stan = <Dodano>

RowAction = Add
Cofnij usuwanie i

Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <niedostępny>

Oryginalny = <przychodzący>

State = Deleted (Stan = <Usunięto)>

RowAction = ChangeOriginal
Niezmienione Current = <Przychodzące>

Oryginalny = <istniejący>

Jeśli nowa wartość jest taka sama jak istniejąca wartość, wówczas

Stan = <niezmienione>

RowAction = nic

Innego

State = Modified (Stan = <Zmodyfikowany)>

RowAction = Change
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Nie ma) Current = <Przychodzące>

Oryginalny = <niedostępny>

Stan = <Dodano>

RowAction = Add
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal
Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <niezmienione>

RowAction = ChangeCurrentAndOriginal

Wartości w obiekcie DataColumn można ograniczyć za pomocą właściwości, takich jak ReadOnly i AutoIncrement. Metoda Load obsługuje takie kolumny w sposób zgodny z zachowaniem zdefiniowanym przez właściwości kolumny. Ograniczenie tylko do odczytu dla elementu DataColumn ma zastosowanie tylko w przypadku zmian występujących w pamięci. W Load razie potrzeby metoda zastępuje wartości kolumn tylko do odczytu.

Jeśli podczas wywoływania Load metody określisz opcje OverwriteChanges lub PreserveChanges, zakłada się, że dane przychodzące pochodzą z podstawowego DataTableźródła danych, a tabela DataTable śledzi zmiany i może propagować zmiany z powrotem do źródła danych. W przypadku wybrania opcji Upsert zakłada się, że dane pochodzą z jednego z pomocniczych źródeł danych, takich jak dane dostarczane przez składnik warstwy środkowej, być może zmienione przez użytkownika. W takim przypadku założeniem jest to, że celem jest agregowanie danych z co najmniej jednego źródła danych w DataTableobiekcie , a następnie propagowanie danych z powrotem do podstawowego źródła danych. Parametr LoadOption służy do określania konkretnej wersji wiersza, który ma być używany do porównania klucza podstawowego. Poniższa tabela zawiera szczegółowe informacje.

Opcja ładowania Wersja elementu DataRow używana na potrzeby porównania klucza podstawowego
OverwriteChanges Oryginalna wersja, jeśli istnieje, w przeciwnym razie bieżąca wersja
PreserveChanges Oryginalna wersja, jeśli istnieje, w przeciwnym razie bieżąca wersja
Upsert Bieżąca wersja, jeśli istnieje, w przeciwnym razie oryginalna wersja

Parametr errorHandler to FillErrorEventHandler delegat, który odwołuje się do procedury wywoływanej w przypadku wystąpienia błędu podczas ładowania danych. Parametr FillErrorEventArgs przekazany do procedury zawiera właściwości, które umożliwiają pobieranie informacji o błędzie, który wystąpił, bieżący wiersz danych i DataTable wypełniane. Użycie tego mechanizmu delegata, a nie prostszego bloku try/catch, pozwala określić błąd, obsłużyć sytuację i kontynuować przetwarzanie, jeśli chcesz. Parametr FillErrorEventArgs dostarcza Continue właściwość: ustaw tę właściwość, aby wskazać true , że wystąpił błąd i chcesz kontynuować przetwarzanie. Ustaw właściwość na wartość , aby false wskazać, że chcesz zatrzymać przetwarzanie. Należy pamiętać, że ustawienie właściwości powoduje false , że kod, który wyzwolił problem, zgłasza wyjątek.

Zobacz też

Dotyczy