Udostępnij za pośrednictwem


DataSet.Load Metoda

Definicja

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanego IDataReaderelementu .

Przeciążenia

Nazwa Opis
Load(IDataReader, LoadOption, DataTable[])

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanej IDataReadermetody , używając tablicy DataTable wystąpień w celu dostarczenia informacji o schemacie i przestrzeni nazw.

Load(IDataReader, LoadOption, String[])

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanej IDataReadermetody , używając tablicy ciągów w celu podania nazw tabel w obiekcie DataSet.

Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[])

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanej IDataReadermetody , używając tablicy DataTable wystąpień w celu dostarczenia informacji o schemacie i przestrzeni nazw.

Uwagi

Metoda Load zapewnia technikę wypełniania pojedynczego z DataTable danymi pobranymi IDataReader z wystąpienia. Ta metoda zapewnia tę samą funkcjonalność, ale umożliwia ładowanie wielu zestawów wyników z IDataReader elementu do wielu tabel w obrębie DataSet.

Jeśli obiekt DataSet zawiera już wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami.

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 ).DataSet W tych scenariuszach opisano standardowe użycie elementu DataSet, opisując jego działanie aktualizacji i scalania.

Synchronizacja DataSet lub aktualizacje z jednym podstawowym źródłem danych. Śledzi DataSet zmiany, umożliwiając synchronizację z podstawowym źródłem danych. Ponadto obiekt DataSet może akceptować dane przyrostowe z co najmniej jednego pomocniczego źródła danych. Element DataSet 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 DataSet z podstawowego źródła danych. W tym scenariuszu użytkownik chce zainicjować pusty DataSet element z wartościami z podstawowego źródła danych. Zawartość co najmniej jednej tabeli DataTable jest modyfikowana. 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ć DataSet wypełnioną w poprzednim scenariuszu synchronizację przyrostową z podstawowym źródłem danych, zachowując modyfikacje wprowadzone w pliku DataSet.

  • 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. Ta metoda umożliwia określenie parametru opcji ładowania wskazującego, jak wiersze już w połączeniu DataTable z ładowanymi wierszami. 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, LoadOption, DataTable[])

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

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanej IDataReadermetody , używając tablicy DataTable wystąpień w celu dostarczenia informacji o schemacie i przestrzeni nazw.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, ... cli::array <System::Data::DataTable ^> ^ tables);
[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, params System.Data.DataTable[] tables);
public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, params System.Data.DataTable[] tables);
[<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 * System.Data.DataTable[] -> unit
member this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.DataTable[] -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption, ParamArray tables As DataTable())

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 znajdujące się już w DataTable wystąpieniach w obiekcie DataSet zostaną połączone z wierszami przychodzącymi, które współużytkują ten sam klucz podstawowy.

tables
DataTable[]

Tablica DataTable wystąpień, z których Load(IDataReader, LoadOption, DataTable[]) metoda pobiera informacje o nazwie i przestrzeni nazw. Każda z tych tabel musi być elementem członkowskim zawartym w tym elemencie DataTableCollectionDataSet.

Atrybuty

Przykłady

Poniższy przykład tworzy nowy DataSetelement , dodaje dwa DataTable wystąpienia do DataSetklasy , a następnie wypełnia DataSet metodę przy użyciu Load metody , pobierając dane z elementu zawierającego DataTableReader dwa zestawy wyników. Na koniec w przykładzie zostanie wyświetlona zawartość tabel w oknie konsoli.

static void Main()
{
    DataSet dataSet = new DataSet();

    DataTable customerTable = new DataTable();
    DataTable productTable = new DataTable();

    // This information is cosmetic, only.
    customerTable.TableName = "Customers";
    productTable.TableName = "Products";

    // Add the tables to the DataSet:
    dataSet.Tables.Add(customerTable);
    dataSet.Tables.Add(productTable);

    // Load the data into the existing DataSet.
    DataTableReader reader = GetReader();
    dataSet.Load(reader, LoadOption.OverwriteChanges,
        customerTable, productTable);

    // Print out the contents of each table:
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

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

private static DataTable GetCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();
    table.TableName = "Customers";

    // 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 GetProducts()
{
    // Create sample Products table.
    DataTable table = new DataTable();
    table.TableName = "Products";

    // 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, "Wireless Network Card" });
    table.Rows.Add(new object[] { 1, "Hard Drive" });
    table.Rows.Add(new object[] { 2, "Monitor" });
    table.Rows.Add(new object[] { 3, "CPU" });
    table.AcceptChanges();
    return table;
}

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

private static DataTableReader GetReader()
{
    // Return a DataTableReader containing multiple
    // result sets, just for the sake of this demo.
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());
    return dataSet.CreateDataReader();
}
Sub Main()
    Dim dataSet As New DataSet

    Dim customerTable As New DataTable
    Dim productTable As New DataTable

    ' This information is cosmetic, only.
    customerTable.TableName = "Customers"
    productTable.TableName = "Products"

    ' Add the tables to the DataSet:
    dataSet.Tables.Add(customerTable)
    dataSet.Tables.Add(productTable)

    ' Load the data into the existing DataSet. 
    Dim reader As DataTableReader = GetReader()
    dataSet.Load(reader, LoadOption.OverwriteChanges, _
        customerTable, productTable)

    ' Print out the contents of each table:
    For Each table As DataTable In dataSet.Tables
        PrintColumns(table)
    Next

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

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

    ' 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 GetProducts() As DataTable
    ' Create sample Products table, in order
    ' to demonstrate the behavior of the DataTableReader.
    Dim table As New DataTable
    table.TableName = "Products"

    ' 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, "Wireless Network Card"})
    table.Rows.Add(New Object() {1, "Hard Drive"})
    table.Rows.Add(New Object() {2, "Monitor"})
    table.Rows.Add(New Object() {3, "CPU"})
    Return table
End Function

Private Function GetReader() As DataTableReader
    ' Return a DataTableReader containing multiple
    ' result sets, just for the sake of this demo.
    Dim dataSet As New DataSet
    dataSet.Tables.Add(GetCustomers())
    dataSet.Tables.Add(GetProducts())
    Return dataSet.CreateDataReader()
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

    Console.WriteLine()
    Console.WriteLine(table.TableName)
    Console.WriteLine("=========================")
    ' Loop through all the rows in the table.
    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 zapewnia technikę wypełniania pojedynczego z DataTable danymi pobranymi IDataReader z wystąpienia. Ta metoda zapewnia tę samą funkcjonalność, ale umożliwia ładowanie wielu zestawów wyników z IDataReader elementu do wielu tabel w obrębie DataSet.

Uwaga / Notatka

Operacja ładowania zakończy się niepowodzeniem InvalidOperationException , jeśli którakolwiek z kolumn danych źródłowych w przychodzących reader kolumnach jest obliczana.

Parametr loadOption umożliwia określenie sposobu interakcji zaimportowanych danych z istniejącymi danymi i może być dowolną wartością LoadOption z wyliczenia. Aby uzyskać więcej informacji na temat używania tego parametru, zobacz dokumentację DataTableLoad metody .

Parametr tables umożliwia określenie tablicy DataTable wystąpień wskazujących kolejność tabel odpowiadających każdemu zestawowi wyników załadowanemu z czytnika. Metoda Load wypełnia każde dostarczone DataTable wystąpienie danymi z pojedynczego zestawu wyników z czytnika danych źródłowych. Po każdym zestawie Load wyników metoda przechodzi do następnego zestawu wyników w czytniku, dopóki nie będzie więcej zestawów wyników.

Schemat rozpoznawania nazw dla tej metody jest taki sam jak po FillDbDataAdapter metodzie klasy .

Zobacz też

Dotyczy

Load(IDataReader, LoadOption, String[])

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

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanej IDataReadermetody , używając tablicy ciągów w celu podania nazw tabel w obiekcie DataSet.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, ... cli::array <System::String ^> ^ tables);
[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, params string[] tables);
public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, params string[] tables);
[<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 * string[] -> unit
member this.Load : System.Data.IDataReader * System.Data.LoadOption * string[] -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption, ParamArray tables As String())

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 znajdujące się już w DataTable wystąpieniach w obiekcie DataSet zostaną połączone z wierszami przychodzącymi, które współużytkują ten sam klucz podstawowy.

tables
String[]

Tablica ciągów, z których Load metoda pobiera informacje o nazwie tabeli.

Atrybuty

Przykłady

Poniższy przykład aplikacji konsolowej najpierw tworzy tabele i ładuje dane z czytnika do DataSetmetody przy użyciu Load metody . Następnie przykład dodaje tabele do obiektu DataSet i próbuje wypełnić tabele danymi z obiektu DataTableReader. W tym przykładzie, ponieważ parametry przekazane do Load metody wskazują nazwę tabeli, która nie istnieje, Load metoda tworzy nową tabelę, aby dopasować nazwę przekazaną jako parametr. Po załadowaniu danych w przykładzie zostanie wyświetlona zawartość wszystkich jego tabel w oknie Konsola.

static void Main()
{
    DataSet dataSet = new DataSet();

    DataTableReader reader = GetReader();

    // The tables listed as parameters for the Load method
    // should be in the same order as the tables within the IDataReader.
    dataSet.Load(reader, LoadOption.Upsert, "Customers", "Products");
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

    // Now try the example with the DataSet
    // already filled with data:
    dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());

    // Retrieve a data reader containing changed data:
    reader = GetReader();

    // Load the data into the existing DataSet. Retrieve the order of the
    // the data in the reader from the
    // list of table names in the parameters. If you specify
    // a new table name here, the Load method will create
    // a corresponding new table.
    dataSet.Load(reader, LoadOption.Upsert,
        "NewCustomers", "Products");
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

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

private static DataTable GetCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();
    table.TableName = "Customers";

    // 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 GetProducts()
{
    // Create sample Products table.
    DataTable table = new DataTable();
    table.TableName = "Products";

    // 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, "Wireless Network Card" });
    table.Rows.Add(new object[] { 1, "Hard Drive" });
    table.Rows.Add(new object[] { 2, "Monitor" });
    table.Rows.Add(new object[] { 3, "CPU" });
    table.AcceptChanges();
    return table;
}

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

private static DataTableReader GetReader()
{
    // Return a DataTableReader containing multiple
    // result sets, just for the sake of this demo.
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());
    return dataSet.CreateDataReader();
}
Sub Main()
  Dim dataSet As New DataSet
  Dim table As DataTable

  Dim reader As DataTableReader = GetReader()

  ' The tables listed as parameters for the Load method 
  ' should be in the same order as the tables within the IDataReader.
  dataSet.Load(reader, LoadOption.Upsert, "Customers", "Products")
  For Each table In dataSet.Tables
    PrintColumns(table)
  Next

  ' Now try the example with the DataSet
  ' already filled with data:
  dataSet = New DataSet
  dataSet.Tables.Add(GetCustomers())
  dataSet.Tables.Add(GetProducts())

  ' Retrieve a data reader containing changed data:
  reader = GetReader()

  ' Load the data into the existing DataSet. Retrieve the order of the
  ' the data in the reader from the
  ' list of table names in the parameters. If you specify
  ' a new table name here, the Load method will create
  ' a corresponding new table.
  dataSet.Load(reader, LoadOption.Upsert, "NewCustomers", "Products")
  For Each table In dataSet.Tables
    PrintColumns(table)
  Next

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

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

  ' 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 GetProducts() As DataTable
  ' Create sample Products table, in order
  ' to demonstrate the behavior of the DataTableReader.
  Dim table As New DataTable
  table.TableName = "Products"

  ' 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, "Wireless Network Card"})
  table.Rows.Add(New Object() {1, "Hard Drive"})
  table.Rows.Add(New Object() {2, "Monitor"})
  table.Rows.Add(New Object() {3, "CPU"})
  Return table
End Function

Private Function GetReader() As DataTableReader
  ' Return a DataTableReader containing multiple
  ' result sets, just for the sake of this demo.
  Dim dataSet As New DataSet
  dataSet.Tables.Add(GetCustomers())
  dataSet.Tables.Add(GetProducts())
  Return dataSet.CreateDataReader()
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

  Console.WriteLine()
  Console.WriteLine(table.TableName)
  Console.WriteLine("=========================")
  ' Loop through all the rows in the table.
  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 zapewnia technikę wypełniania pojedynczego z DataTable danymi pobranymi IDataReader z wystąpienia. Ta metoda zapewnia tę samą funkcjonalność, ale umożliwia ładowanie wielu zestawów wyników z IDataReader elementu do wielu tabel w obrębie DataSet.

Uwaga / Notatka

Operacja ładowania zakończy się niepowodzeniem InvalidOperationException , jeśli którakolwiek z kolumn danych źródłowych w przychodzących reader kolumnach jest obliczana.

Parametr loadOption umożliwia określenie sposobu interakcji zaimportowanych danych z istniejącymi danymi i może być dowolną wartością LoadOption z wyliczenia. Aby uzyskać więcej informacji na temat używania tego parametru, zobacz dokumentację Load metody .

Parametr tables umożliwia określenie tablicy nazw tabel wskazujących kolejność tabel odpowiadających każdemu zestawowi wyników załadowanemu z czytnika. Metoda Load próbuje znaleźć tabelę w DataSet pasującej nazwie znalezionej w tablicy nazw tabel w kolejności. Jeśli zostanie znaleziona pasująca tabela, ta tabela zostanie załadowana z zawartością bieżącego zestawu wyników. Jeśli tabela nie zostanie znaleziona, zostanie utworzona tabela przy użyciu nazwy podanej w tablicy nazw tabel, a schemat nowej tabeli zostanie wywnioskowany z zestawu wyników. Po każdym zestawie Load wyników metoda przechodzi do następnego zestawu wyników w czytniku, dopóki nie będzie więcej zestawów wyników.

Domyślna przestrzeń nazw skojarzona z elementem DataSet, jeśli istnieje, jest skojarzona z każdym nowo utworzonym elementem DataTable. Schemat rozpoznawania nazw dla tej metody jest taki sam jak po FillDbDataAdapter metodzie klasy .

Zobacz też

Dotyczy

Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[])

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

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanej IDataReadermetody , używając tablicy DataTable wystąpień w celu dostarczenia informacji o schemacie i przestrzeni nazw.

public:
 virtual void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, System::Data::FillErrorEventHandler ^ errorHandler, ... cli::array <System::Data::DataTable ^> ^ tables);
[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, params System.Data.DataTable[] tables);
public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler? errorHandler, params System.Data.DataTable[] tables);
public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler, params System.Data.DataTable[] tables);
[<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 * System.Data.DataTable[] -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler * System.Data.DataTable[] -> unit
abstract member Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler * System.Data.DataTable[] -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler * System.Data.DataTable[] -> unit
Public Overridable Sub Load (reader As IDataReader, loadOption As LoadOption, errorHandler As FillErrorEventHandler, ParamArray tables As DataTable())

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 znajdujące się już w DataTable wystąpieniach w obiekcie DataSet zostaną połą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.

tables
DataTable[]

Tablica DataTable wystąpień, z których Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) metoda pobiera informacje o nazwie i przestrzeni nazw.

Atrybuty

Przykłady

Poniższy przykład dodaje tabelę do DataSetobiektu , a następnie próbuje użyć Load metody w celu załadowania danych z obiektu DataTableReader zawierającego niezgodny schemat. Zamiast podlewać błąd, w tym przykładzie użyto delegata FillErrorEventHandler do zbadania i obsługi błędu. Dane wyjściowe są wyświetlane w oknie konsoli.

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.:
    DataSet dataSet = new DataSet();
    DataTable table = GetIntegerTable();
    dataSet.Tables.Add(table);
    DataTableReader reader = new DataTableReader(GetStringTable());
    dataSet.Load(reader, LoadOption.OverwriteChanges,
        FillErrorHandler, table);

    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 dataSet As New DataSet
  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.:
  dataSet = New DataSet()
  table = GetIntegerTable()
  dataSet.Tables.Add(table)
  Dim reader As New DataTableReader(GetStringTable())
  dataSet.Load(reader, LoadOption.OverwriteChanges, _
      AddressOf FillErrorHandler, table)

  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 zapewnia technikę wypełniania pojedynczego z DataTable danymi pobranymi IDataReader z wystąpienia. Ta metoda zapewnia tę samą funkcjonalność, ale umożliwia ładowanie wielu zestawów wyników z IDataReader elementu do wielu tabel w obrębie DataSet.

Uwaga / Notatka

Operacja ładowania zakończy się niepowodzeniem InvalidOperationException , jeśli którakolwiek z kolumn danych źródłowych w przychodzących reader kolumnach jest obliczana.

Parametr loadOption umożliwia określenie sposobu interakcji zaimportowanych danych z istniejącymi danymi i może być dowolną wartością LoadOption z wyliczenia. Aby uzyskać więcej informacji na temat używania tego parametru, zobacz dokumentację DataTableLoad metody .

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 true wskazać, że wystąpił błąd i chcesz kontynuować przetwarzanie. Ustaw właściwość na false wartość , aby 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.

Parametr tables umożliwia określenie tablicy DataTable wystąpień wskazujących kolejność tabel odpowiadających każdemu zestawowi wyników załadowanemu z czytnika. Metoda Load wypełnia każde dostarczone DataTable wystąpienie danymi z pojedynczego zestawu wyników z czytnika danych źródłowych. Po każdym zestawie Load wyników metoda przechodzi do następnego zestawu wyników w czytniku, dopóki nie będzie więcej zestawów wyników.

Schemat rozpoznawania nazw dla tej metody jest taki sam jak po FillDbDataAdapter metodzie klasy .

Zobacz też

Dotyczy