DataSet.Load Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Preenche a DataSet com valores de uma fonte de dados usando o .IDataReader
Sobrecargas
| Name | Description |
|---|---|
| Load(IDataReader, LoadOption, DataTable[]) |
Preenche a DataSet com valores de uma fonte de dados usando o fornecido IDataReader, usando um array de DataTable instâncias para fornecer a informação do esquema e do namespace. |
| Load(IDataReader, LoadOption, String[]) |
Preenche a DataSet com valores de uma fonte de dados usando o fornecido IDataReader, usando um array de cadeias para fornecer os nomes das tabelas dentro do |
| Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) |
Preenche a DataSet com valores de uma fonte de dados usando o fornecido IDataReader, usando um array de DataTable instâncias para fornecer a informação do esquema e do namespace. |
Observações
O Load método fornece uma técnica para preencher um único DataTable com dados, recuperados de uma IDataReader instância. Este método oferece a mesma funcionalidade, mas permite carregar múltiplos conjuntos de resultados de um IDataReader para múltiplas tabelas dentro de um DataSet.
Se já DataSet contiver linhas, os dados recebidos da fonte de dados são fundidos com as linhas existentes.
O Load método pode ser usado em vários cenários comuns, todos centrados em obter dados de uma fonte de dados especificada e adicioná-los ao contentor de dados atual (neste caso, um DataSet). Estes cenários descrevem o uso padrão para um DataSet, descrevendo o seu comportamento de atualização e fusão.
A DataSet sincroniza-se ou atualiza-se com uma única fonte de dados primária. As DataSet trilhas mudam, permitindo a sincronização com a fonte de dados principal. Além disso, pode DataSet aceitar dados incrementais de uma ou mais fontes secundárias de dados. Não DataSet é responsável por acompanhar as alterações para permitir a sincronização com a fonte secundária de dados.
Dadas estas duas fontes de dados hipotéticas, é provável que um utilizador necessite de um dos seguintes comportamentos:
Inicialize
DataSeta partir de uma fonte de dados primária. Neste cenário, o utilizador quer inicializar um vazioDataSetcom valores da fonte de dados primária. Um ou mais conteúdos do DataTable são modificados. Mais tarde, o utilizador pretende propagar as alterações de volta à fonte principal de dados.Preservar as alterações e voltar a sincronizar a partir da fonte de dados principal. Neste cenário, o utilizador quer pegar no
DataSetpreenchimento do cenário anterior e realizar uma sincronização incremental com a fonte de dados principal, preservando as modificações feitas noDataSet.Alimentação incremental de dados a partir de fontes secundárias. Neste cenário, o utilizador pretende fundir alterações de uma ou mais fontes secundárias de dados e propagar essas alterações de volta à fonte de dados primária.
O Load método torna todos estes cenários possíveis. Este método permite-lhe especificar um parâmetro de opção de carga, indicando como as linhas já existentes DataTable se combinam com as linhas a serem carregadas. A tabela seguinte descreve as três opções de carregamento fornecidas pela LoadOption enumeração. Em cada caso, a descrição indica o comportamento quando a chave primária de uma linha nos dados recebidos corresponde à chave primária de uma linha existente.
| Opção de Carga | Description |
|---|---|
PreserveChanges (padrão) |
Atualiza a versão original da linha com o valor da linha recebida. |
OverwriteChanges |
Atualiza as versões atuais e originais da linha com o valor da linha recebida. |
Upsert |
Atualiza a versão atual da linha com o valor da linha recebida. |
Em geral, as PreserveChanges opções e OverwriteChanges destinam-se a cenários em que o utilizador precisa de sincronizar e DataSet as suas alterações com a fonte de dados principal. A Upsert opção facilita a agregação de alterações de uma ou mais fontes secundárias de dados.
Load(IDataReader, LoadOption, DataTable[])
Preenche a DataSet com valores de uma fonte de dados usando o fornecido IDataReader, usando um array de DataTable instâncias para fornecer a informação do esquema e do namespace.
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())
Parâmetros
- reader
- IDataReader
E IDataReader que forneça um ou mais conjuntos de resultados.
- loadOption
- LoadOption
Um valor da LoadOption enumeração que indica como as linhas já existentes nas DataTable instâncias serão DataSet combinadas com as linhas de entrada que partilham a mesma chave primária.
- tables
- DataTable[]
Um array de DataTable instâncias, a partir do qual o Load(IDataReader, LoadOption, DataTable[]) método recupera informação de nome e espaço de nomes. Cada uma destas tabelas deve ser um membro do DataTableCollection contido por este DataSet.
Exemplos
O exemplo seguinte cria um novo DataSet, adiciona duas DataTable instâncias ao DataSet, e depois preenche o DataSet usando o Load método, recuperando dados de um DataTableReader que contém dois conjuntos de resultados. Finalmente, o exemplo mostra o conteúdo das tabelas na janela da consola.
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
Observações
O Load método fornece uma técnica para preencher um único DataTable com dados, recuperados de uma IDataReader instância. Este método oferece a mesma funcionalidade, mas permite carregar múltiplos conjuntos de resultados de um IDataReader para múltiplas tabelas dentro de um DataSet.
Note
A operação de carregamento falhará com um InvalidOperationException se alguma das colunas de dados de origem na entrada reader for uma coluna computada.
O loadOption parâmetro permite-lhe especificar como quer que os dados importados interajam com dados existentes, podendo ser qualquer um dos valores da LoadOption enumeração. Consulte a documentação do DataTableLoad método para mais informações sobre a utilização deste parâmetro.
O tables parâmetro permite especificar um array de DataTable instâncias, indicando a ordem das tabelas correspondentes a cada conjunto de resultados carregado pelo leitor. O Load método preenche cada instância fornecida DataTable com dados de um único conjunto de resultados do leitor de dados de origem. Após cada conjunto de resultados, o Load método passa para o conjunto seguinte dentro do leitor, até que não haja mais conjuntos de resultados.
O esquema de resolução de nomes para este método é o mesmo seguido pelo Fill método da DbDataAdapter classe.
Ver também
Aplica-se a
Load(IDataReader, LoadOption, String[])
Preenche a DataSet com valores de uma fonte de dados usando o fornecido IDataReader, usando um array de cadeias para fornecer os nomes das tabelas dentro do 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())
Parâmetros
- reader
- IDataReader
E IDataReader que forneça um ou mais conjuntos de resultados.
- loadOption
- LoadOption
Um valor da LoadOption enumeração que indica como as linhas já existentes nas DataTable instâncias serão DataSet combinadas com as linhas de entrada que partilham a mesma chave primária.
- tables
- String[]
Um array de cadeias, a partir do qual o Load método recupera informação do nome da tabela.
Exemplos
O seguinte exemplo de aplicação Consola cria primeiro tabelas e carrega dados de um leitor para um DataSet, usando o Load método. O exemplo então adiciona tabelas a DataSet e tenta preencher as tabelas com dados de um DataTableReader. Neste exemplo, como os parâmetros passados ao Load método indicam um nome de tabela que não existe, o Load método cria uma nova tabela para corresponder ao nome passado como parâmetro. Depois de os dados terem sido carregados, o exemplo mostra o conteúdo de todas as suas tabelas na janela da Consola.
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
Observações
O Load método fornece uma técnica para preencher um único DataTable com dados, recuperados de uma IDataReader instância. Este método oferece a mesma funcionalidade, mas permite carregar múltiplos conjuntos de resultados de um IDataReader para múltiplas tabelas dentro de um DataSet.
Note
A operação de carregamento falhará com um InvalidOperationException se alguma das colunas de dados de origem na entrada reader for uma coluna computada.
O loadOption parâmetro permite-lhe especificar como quer que os dados importados interajam com dados existentes, podendo ser qualquer um dos valores da LoadOption enumeração. Consulte a documentação do Load método para mais informações sobre a utilização deste parâmetro.
O tables parâmetro permite especificar um array de nomes de tabelas, indicando a ordem das tabelas correspondentes a cada conjunto de resultados carregado pelo leitor. O Load método tenta encontrar uma tabela dentro do DataSet que corresponde ao nome encontrado no array de nomes de tabelas, por ordem. Se for encontrada uma tabela correspondente, essa tabela é carregada com o conteúdo do conjunto de resultados atual. Se não for encontrada nenhuma tabela correspondente, uma tabela é criada usando o nome fornecido no array de nomes de tabelas, e o esquema da nova tabela é inferido a partir do conjunto de resultados. Após cada conjunto de resultados, o Load método passa para o conjunto seguinte dentro do leitor, até que não haja mais conjuntos de resultados.
O namespace padrão associado a DataSet, se existir, está associado a cada novo DataTable. O esquema de resolução de nomes para este método é o mesmo seguido pelo Fill método da DbDataAdapter classe.
Ver também
Aplica-se a
Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[])
Preenche a DataSet com valores de uma fonte de dados usando o fornecido IDataReader, usando um array de DataTable instâncias para fornecer a informação do esquema e do namespace.
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);
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())
Parâmetros
- reader
- IDataReader
E IDataReader que forneça um ou mais conjuntos de resultados.
- loadOption
- LoadOption
Um valor da LoadOption enumeração que indica como as linhas já existentes nas DataTable instâncias serão DataSet combinadas com as linhas de entrada que partilham a mesma chave primária.
- errorHandler
- FillErrorEventHandler
Um delegado para chamar quando ocorre um erro durante o FillErrorEventHandler carregamento de dados.
- tables
- DataTable[]
Um array de DataTable instâncias, a partir do qual o Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) método recupera informação de nome e espaço de nomes.
Exemplos
O exemplo seguinte adiciona uma tabela a DataSetum , e depois tenta usar o Load método para carregar dados de um DataTableReader que contenham um esquema incompatível. Em vez de capturar o erro, este exemplo usa um FillErrorEventHandler delegado para investigar e tratar o erro. A saída é exibida na janela da consola.
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
Observações
O Load método fornece uma técnica para preencher um único DataTable com dados, recuperados de uma IDataReader instância. Este método oferece a mesma funcionalidade, mas permite carregar múltiplos conjuntos de resultados de um IDataReader para múltiplas tabelas dentro de um DataSet.
Note
A operação de carregamento falhará com um InvalidOperationException se alguma das colunas de dados de origem na entrada reader for uma coluna computada.
O loadOption parâmetro permite-lhe especificar como quer que os dados importados interajam com dados existentes, podendo ser qualquer um dos valores da LoadOption enumeração. Consulte a documentação do DataTableLoad método para mais informações sobre a utilização deste parâmetro.
O errorHandler parâmetro é um FillErrorEventHandler delegado que se refere a um procedimento chamado quando ocorre um erro durante o carregamento de dados. O FillErrorEventArgs parâmetro passado ao procedimento fornece propriedades que permitem recuperar informações sobre o erro que ocorreu, a linha atual de dados e o DataTable preenchimento. Usar este mecanismo de delegado, em vez de um bloqueio try/catch mais simples, permite-lhe determinar o erro, lidar com a situação e continuar a processar, se quiser. O FillErrorEventArgs parâmetro fornece uma Continue propriedade: defina esta propriedade para true indicar que tratou o erro e deseja continuar o processamento; defina a propriedade para false indicar que deseja parar o processamento. Tenha em atenção que definir a propriedade para false faz com que o código que desencadeou o problema lance uma exceção.
O tables parâmetro permite especificar um array de DataTable instâncias, indicando a ordem das tabelas correspondentes a cada conjunto de resultados carregado pelo leitor. O Load método preenche cada instância fornecida DataTable com dados de um único conjunto de resultados do leitor de dados de origem. Após cada conjunto de resultados, o Load método passa para o conjunto seguinte dentro do leitor, até que não haja mais conjuntos de resultados.
O esquema de resolução de nomes para este método é o mesmo seguido pelo Fill método da DbDataAdapter classe.