DataSet.Load Metoda

Definicja

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

Przeciążenia

Load(IDataReader, LoadOption, DataTable[])

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanego IDataReaderelementu , używając tablicy DataTable wystąpień w celu podania 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 podanego IDataReaderelementu , używając tablicy DataTable wystąpień w celu podania informacji o schemacie i przestrzeni nazw.

Uwagi

Metoda Load zapewnia technikę wypełniania pojedynczego DataTable za pomocą danych pobranych 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 zostaną scalone z istniejącymi wierszami.

Metoda Load może być używana 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 Te scenariusze opisują standardowe użycie elementu DataSet, opisując jego zachowanie aktualizacji i scalania.

Element DataSet synchronizuje się lub aktualizuje 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ń:

  • Inicjowanie 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ć wypełnioną DataSet 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 są już ładowane w połączeniu DataTable z wierszami. W poniższej tabeli opisano trzy opcje ładowania udostępniane przez wyliczenie LoadOption . 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 (wartość domyślna) Aktualizuje oryginalną wersję wiersza z 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[])

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

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, ... cli::array <System::Data::DataTable ^> ^ tables);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, params System.Data.DataTable[] tables);
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, jak wiersze znajdujące się już w wystąpieniach w DataTable 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órej Load(IDataReader, LoadOption, DataTable[]) metoda pobiera informacje o nazwie i przestrzeni nazw. Każda z tych tabel musi być elementem członkowskim DataTableCollection zawartym w tym elemencie DataSet.

Przykłady

Poniższy przykład tworzy nowy DataSetelement , dodaje dwa DataTable wystąpienia do DataSetklasy , a następnie wypełnia DataSet metodę Load przy użyciu metody, pobierając dane z zestawu DataTableReader wyników zawierającego dwa zestawy wyników. Na koniec przykład wyświetla 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 z IDataReader wystąpienia. Ta metoda zapewnia tę samą funkcjonalność, ale umożliwia ładowanie wielu zestawów wyników z wielu IDataReader tabel w obrębie DataSet.

Uwaga

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ą z wyliczenia LoadOption . 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ładowanym 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 ma więcej zestawów wyników.

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

Zobacz też

Dotyczy

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.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, ... cli::array <System::String ^> ^ tables);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, params string[] tables);
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, jak wiersze znajdujące się już w wystąpieniach w DataTable 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órej Load metoda pobiera informacje o nazwie tabeli.

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 tabeli DataSet i próbuje wypełnić tabele danymi z elementu DataTableReader. W tym przykładzie, ponieważ parametry przekazane do Load metody wskazują nazwę tabeli, która nie istnieje, Load metoda tworzy nową tabelę zgodną z 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 z IDataReader wystąpienia. Ta metoda zapewnia tę samą funkcjonalność, ale umożliwia ładowanie wielu zestawów wyników z wielu IDataReader tabel w obrębie DataSet.

Uwaga

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ą z wyliczenia LoadOption . 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ładowanym z czytnika. Metoda Load próbuje znaleźć tabelę w pasującej nazwie znalezionej DataSet 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 nie znaleziono pasującej tabeli, 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 ma więcej zestawów wyników.

Domyślna przestrzeń nazw skojarzona z elementem , jeśli istnieje, jest skojarzona z DataSetkażdą nowo utworzoną DataTableprzestrzenią nazw. Schemat rozpoznawania nazw dla tej metody jest taki sam jak Fill po metodzie DbDataAdapter klasy .

Zobacz też

Dotyczy

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

Wypełnia element DataSet wartościami ze źródła danych przy użyciu podanego IDataReaderelementu , używając tablicy DataTable wystąpień w celu podania 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);
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);
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, jak wiersze znajdujące się już w wystąpieniach w DataTable 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, gdy wystąpi błąd podczas ładowania danych.

tables
DataTable[]

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

Przykłady

Poniższy przykład dodaje tabelę do obiektu DataSet, a następnie próbuje użyć Load metody w celu załadowania danych z DataTableReader obiektu zawierającego niezgodny schemat. Zamiast uwięzić 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 z IDataReader wystąpienia. Ta metoda zapewnia tę samą funkcjonalność, ale umożliwia ładowanie wielu zestawów wyników z wielu IDataReader tabel w obrębie DataSet.

Uwaga

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ą z wyliczenia LoadOption . Aby uzyskać więcej informacji na temat używania tego parametru, zobacz dokumentację DataTableLoad metody .

Parametr errorHandler jest delegatem FillErrorEventHandler , 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. Korzystanie z tego mechanizmu delegata, a nie prostszego bloku try/catch, umożliwia określenie błędu, obsługę sytuacji i kontynuowanie przetwarzania, 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 wartość , aby wskazać false , ż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ładowanym 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 ma więcej zestawów wyników.

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

Zobacz też

Dotyczy