DataTable.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 DataTable com valores de uma fonte de dados usando o .IDataReader Se já DataTable contiver linhas, os dados recebidos da fonte de dados são fundidos com as linhas existentes.
Sobrecargas
| Name | Description |
|---|---|
| Load(IDataReader) |
Preenche a DataTable com valores de uma fonte de dados usando o .IDataReader Se já DataTable contiver linhas, os dados recebidos da fonte de dados são fundidos com as linhas existentes. |
| Load(IDataReader, LoadOption) |
Preenche a DataTable com valores de uma fonte de dados usando o .IDataReader Se já |
| Load(IDataReader, LoadOption, FillErrorEventHandler) |
Preenche a DataTable com valores de uma fonte de dados usando o fornecido IDataReader usando um delegado de gestão de erros. |
Exemplos
O exemplo seguinte demonstra várias das questões envolvidas em chamar o Load método. Primeiro, o exemplo foca-se em questões de esquema, incluindo inferir um esquema a partir do carregamento IDataReader, e depois tratar esquemas incompatíveis e esquemas com colunas em falta ou adicionais. O exemplo foca-se então em questões de dados, incluindo a gestão das várias opções de carregamento.
Note
Este exemplo mostra como usar uma das versões sobrecarregadas de Load. Para outros exemplos que possam estar disponíveis, veja os tópicos individuais de sobrecarga.
static void Main()
{
// This example examines a number of scenarios involving the
// DataTable.Load method.
Console.WriteLine("Load a DataTable and infer its schema:");
// The table has no schema. The Load method will infer the
// schema from the IDataReader:
DataTable table = new DataTable();
// Retrieve a data reader, based on the Customers data. In
// an application, this data might be coming from a middle-tier
// business object:
DataTableReader reader = new DataTableReader(GetCustomers());
table.Load(reader);
PrintColumns(table);
Console.WriteLine(" ============================= ");
Console.WriteLine("Load a DataTable from an incompatible IDataReader:");
// Create a table with a single integer column. Attempt
// to load data from a reader with a schema that is
// incompatible. Note the exception, determined
// by the particular incompatibility:
table = GetIntegerTable();
reader = new DataTableReader(GetStringTable());
try
{
table.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
}
Console.WriteLine(" ============================= ");
Console.WriteLine(
"Load a DataTable with an IDataReader that has extra columns:");
// Note that loading a reader with extra columns adds
// the columns to the existing table, if possible:
table = GetIntegerTable();
reader = new DataTableReader(GetCustomers());
table.Load(reader);
PrintColumns(table);
Console.WriteLine(" ============================= ");
Console.WriteLine(
"Load a DataTable with an IDataReader that has missing columns:");
// Note that loading a reader with missing columns causes
// the columns to be filled with null data, if possible:
table = GetCustomers();
reader = new DataTableReader(GetIntegerTable());
table.Load(reader);
PrintColumns(table);
// Demonstrate the various possibilites when loading data into
// a DataTable that already contains data.
Console.WriteLine(" ============================= ");
Console.WriteLine("Demonstrate data considerations:");
Console.WriteLine("Current value, Original value, (RowState)");
Console.WriteLine(" ============================= ");
Console.WriteLine("Original table:");
table = SetupModifiedRows();
DisplayRowState(table);
Console.WriteLine(" ============================= ");
Console.WriteLine("Data in IDataReader to be loaded:");
DisplayRowState(GetChangedCustomers());
PerformDemo(LoadOption.OverwriteChanges);
PerformDemo(LoadOption.PreserveChanges);
PerformDemo(LoadOption.Upsert);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static void DisplayRowState(DataTable table)
{
for (int i = 0; i <= table.Rows.Count - 1; i++)
{
object current = "--";
object original = "--";
DataRowState rowState = table.Rows[i].RowState;
// Attempt to retrieve the current value, which doesn't exist
// for deleted rows:
if (rowState != DataRowState.Deleted)
{
current = table.Rows[i]["Name", DataRowVersion.Current];
}
// Attempt to retrieve the original value, which doesn't exist
// for added rows:
if (rowState != DataRowState.Added)
{
original = table.Rows[i]["Name", DataRowVersion.Original];
}
Console.WriteLine("{0}: {1}, {2} ({3})", i, current,
original, rowState);
}
}
private static DataTable GetChangedCustomers()
{
// Create sample Customers table.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 0, "XXX" });
table.Rows.Add(new object[] { 1, "XXX" });
table.Rows.Add(new object[] { 2, "XXX" });
table.Rows.Add(new object[] { 3, "XXX" });
table.Rows.Add(new object[] { 4, "XXX" });
table.AcceptChanges();
return table;
}
private static DataTable GetCustomers()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 0, "Mary" });
table.Rows.Add(new object[] { 1, "Andy" });
table.Rows.Add(new object[] { 2, "Peter" });
table.AcceptChanges();
return table;
}
private static DataTable GetIntegerTable()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 4 });
table.Rows.Add(new object[] { 5 });
table.AcceptChanges();
return table;
}
private static DataTable GetStringTable()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { "Mary" });
table.Rows.Add(new object[] { "Andy" });
table.Rows.Add(new object[] { "Peter" });
table.AcceptChanges();
return table;
}
private static void PerformDemo(LoadOption optionForLoad)
{
// Load data into a DataTable, retrieve a DataTableReader containing
// different data, and call the Load method. Depending on the
// LoadOption value passed as a parameter, this procedure displays
// different results in the DataTable.
Console.WriteLine(" ============================= ");
Console.WriteLine("table.Load(reader, {0})", optionForLoad);
Console.WriteLine(" ============================= ");
DataTable table = SetupModifiedRows();
DataTableReader reader = new DataTableReader(GetChangedCustomers());
table.RowChanging +=new DataRowChangeEventHandler(HandleRowChanging);
table.Load(reader, optionForLoad);
Console.WriteLine();
DisplayRowState(table);
}
private static void PrintColumns(DataTable table)
{
// Loop through all the rows in the DataTableReader
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
Console.Write(row[i] + " ");
}
Console.WriteLine();
}
}
private static DataTable SetupModifiedRows()
{
// Fill a DataTable with customer info, and
// then modify, delete, and add rows.
DataTable table = GetCustomers();
// Row 0 is unmodified.
// Row 1 is modified.
// Row 2 is deleted.
// Row 3 is added.
table.Rows[1]["Name"] = "Sydney";
table.Rows[2].Delete();
DataRow row = table.NewRow();
row["ID"] = 3;
row["Name"] = "Melony";
table.Rows.Add(row);
// Note that the code doesn't call
// table.AcceptChanges()
return table;
}
static void HandleRowChanging(object sender, DataRowChangeEventArgs e)
{
Console.WriteLine(
"RowChanging event: ID = {0}, action = {1}", e.Row["ID"],
e.Action);
}
Sub Main()
Dim table As New DataTable()
' This example examines a number of scenarios involving the
' DataTable.Load method.
Console.WriteLine("Load a DataTable and infer its schema:")
' Retrieve a data reader, based on the Customers data. In
' an application, this data might be coming from a middle-tier
' business object:
Dim reader As New DataTableReader(GetCustomers())
' The table has no schema. The Load method will infer the
' schema from the IDataReader:
table.Load(reader)
PrintColumns(table)
Console.WriteLine(" ============================= ")
Console.WriteLine("Load a DataTable from an incompatible IDataReader:")
' Create a table with a single integer column. Attempt
' to load data from a reader with a schema that is
' incompatible. Note the exception, determined
' by the particular incompatibility:
table = GetIntegerTable()
reader = New DataTableReader(GetStringTable())
Try
table.Load(reader)
Catch ex As Exception
Console.WriteLine(ex.GetType.Name & ":" & ex.Message())
End Try
Console.WriteLine(" ============================= ")
Console.WriteLine( _
"Load a DataTable with an IDataReader that has extra columns:")
' Note that loading a reader with extra columns adds
' the columns to the existing table, if possible:
table = GetIntegerTable()
reader = New DataTableReader(GetCustomers())
table.Load(reader)
PrintColumns(table)
Console.WriteLine(" ============================= ")
Console.WriteLine( _
"Load a DataTable with an IDataReader that has missing columns:")
' Note that loading a reader with missing columns causes
' the columns to be filled with null data, if possible:
table = GetCustomers()
reader = New DataTableReader(GetIntegerTable())
table.Load(reader)
PrintColumns(table)
' Demonstrate the various possibilites when loading data into
' a DataTable that already contains data.
Console.WriteLine(" ============================= ")
Console.WriteLine("Demonstrate data considerations:")
Console.WriteLine("Current value, Original value, (RowState)")
Console.WriteLine(" ============================= ")
Console.WriteLine("Original table:")
table = SetupModifiedRows()
DisplayRowState(table)
Console.WriteLine(" ============================= ")
Console.WriteLine("Data in IDataReader to be loaded:")
DisplayRowState(GetChangedCustomers())
PerformDemo(LoadOption.OverwriteChanges)
PerformDemo(LoadOption.PreserveChanges)
PerformDemo(LoadOption.Upsert)
Console.WriteLine("Press any key to continue.")
Console.ReadKey()
End Sub
Private Sub DisplayRowState(ByVal table As DataTable)
For i As Integer = 0 To table.Rows.Count - 1
Dim current As Object = "--"
Dim original As Object = "--"
Dim rowState As DataRowState = table.Rows(i).RowState
' Attempt to retrieve the current value, which doesn't exist
' for deleted rows:
If rowState <> DataRowState.Deleted Then
current = table.Rows(i)("Name", DataRowVersion.Current)
End If
' Attempt to retrieve the original value, which doesn't exist
' for added rows:
If rowState <> DataRowState.Added Then
original = table.Rows(i)("Name", DataRowVersion.Original)
End If
Console.WriteLine("{0}: {1}, {2} ({3})", i, current, original, rowState)
Next
End Sub
Private Function GetChangedCustomers() As DataTable
' Create sample Customers table.
Dim table As New DataTable
' Create two columns, ID and Name.
Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))
table.Columns.Add("Name", GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {0, "XXX"})
table.Rows.Add(New Object() {1, "XXX"})
table.Rows.Add(New Object() {2, "XXX"})
table.Rows.Add(New Object() {3, "XXX"})
table.Rows.Add(New Object() {4, "XXX"})
table.AcceptChanges()
Return table
End Function
Private Function GetCustomers() As DataTable
' Create sample Customers table.
Dim table As New DataTable
' Create two columns, ID and Name.
Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))
table.Columns.Add("Name", GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {0, "Mary"})
table.Rows.Add(New Object() {1, "Andy"})
table.Rows.Add(New Object() {2, "Peter"})
table.AcceptChanges()
Return table
End Function
Private Function GetIntegerTable() As DataTable
' Create sample table with a single Int32 column.
Dim table As New DataTable
Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {4})
table.Rows.Add(New Object() {5})
table.AcceptChanges()
Return table
End Function
Private Function GetStringTable() As DataTable
' Create sample table with a single String column.
Dim table As New DataTable
Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {"Mary"})
table.Rows.Add(New Object() {"Andy"})
table.Rows.Add(New Object() {"Peter"})
table.AcceptChanges()
Return table
End Function
Private Sub PerformDemo(ByVal optionForLoad As LoadOption)
' Load data into a DataTable, retrieve a DataTableReader containing
' different data, and call the Load method. Depending on the
' LoadOption value passed as a parameter, this procedure displays
' different results in the DataTable.
Console.WriteLine(" ============================= ")
Console.WriteLine("table.Load(reader, {0})", optionForLoad)
Console.WriteLine(" ============================= ")
Dim table As DataTable = SetupModifiedRows()
Dim reader As New DataTableReader(GetChangedCustomers())
AddHandler table.RowChanging, New _
DataRowChangeEventHandler(AddressOf HandleRowChanging)
table.Load(reader, optionForLoad)
Console.WriteLine()
DisplayRowState(table)
End Sub
Private Sub PrintColumns( _
ByVal table As DataTable)
' Loop through all the rows in the DataTableReader.
For Each row As DataRow In table.Rows
For Each col As DataColumn In table.Columns
Console.Write(row(col).ToString() & " ")
Next
Console.WriteLine()
Next
End Sub
Private Function SetupModifiedRows() As DataTable
' Fill a DataTable with customer info, and
' then modify, delete, and add rows.
Dim table As DataTable = GetCustomers()
' Row 0 is unmodified.
' Row 1 is modified.
' Row 2 is deleted.
' Row 3 is added.
table.Rows(1)("Name") = "Sydney"
table.Rows(2).Delete()
Dim row As DataRow = table.NewRow
row("ID") = 3
row("Name") = "Melony"
table.Rows.Add(row)
' Note that the code doesn't call
' table.AcceptChanges()
Return table
End Function
Private Sub HandleRowChanging(ByVal sender As Object, _
ByVal e As System.Data.DataRowChangeEventArgs)
Console.WriteLine( _
"RowChanging event: ID = {0}, action = {1}", e.Row("ID"), _
e.Action)
End Sub
Observações
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 DataTable). Estes cenários descrevem o uso padrão para um DataTable, descrevendo o seu comportamento de atualização e fusão.
A DataTable sincroniza-se ou atualiza-se com uma única fonte de dados primária. As DataTable trilhas mudam, permitindo a sincronização com a fonte de dados principal. Além disso, pode DataTable aceitar dados incrementais de uma ou mais fontes secundárias de dados. Não DataTable é 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
DataTablea partir de uma fonte de dados primária. Neste cenário, o utilizador quer inicializar um vazioDataTablecom valores da fonte de dados primária. 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
DataTablepreenchimento do cenário anterior e realizar uma sincronização incremental com a fonte de dados principal, preservando as modificações feitas noDataTable.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. Todos, exceto um, dos sobrecarregamentos deste método permitem especificar um parâmetro de opção de carga, indicando como as linhas já existentes se DataTable combinam com as linhas a serem carregadas. (A sobrecarga que não permite especificar o comportamento usa a opção de carregamento por defeito.) 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)
Preenche a DataTable com valores de uma fonte de dados usando o .IDataReader Se já DataTable contiver linhas, os dados recebidos da fonte de dados são fundidos com as linhas existentes.
public:
void Load(System::Data::IDataReader ^ reader);
public void Load(System.Data.IDataReader reader);
member this.Load : System.Data.IDataReader -> unit
Public Sub Load (reader As IDataReader)
Parâmetros
- reader
- IDataReader
E IDataReader isso fornece um conjunto de resultados.
Exemplos
O exemplo seguinte demonstra várias das questões envolvidas em chamar o Load método. Primeiro, o exemplo foca-se em questões de esquema, incluindo inferir um esquema a partir do carregamento IDataReader, e depois tratar esquemas incompatíveis e esquemas com colunas em falta ou adicionais. O exemplo chama então o Load método, exibindo os dados antes e depois da operação de carregamento.
static void Main()
{
// This example examines a number of scenarios involving the
// DataTable.Load method.
Console.WriteLine("Load a DataTable and infer its schema:");
// The table has no schema. The Load method will infer the
// schema from the IDataReader:
DataTable table = new DataTable();
// Retrieve a data reader, based on the Customers data. In
// an application, this data might be coming from a middle-tier
// business object:
DataTableReader reader = new DataTableReader(GetCustomers());
table.Load(reader);
PrintColumns(table);
Console.WriteLine(" ============================= ");
Console.WriteLine(
"Load a DataTable from an incompatible IDataReader:");
// Create a table with a single integer column. Attempt
// to load data from a reader with a schema that is
// incompatible. Note the exception, determined
// by the particular incompatibility:
table = GetIntegerTable();
reader = new DataTableReader(GetStringTable());
try
{
table.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
}
Console.WriteLine(" ============================= ");
Console.WriteLine(
"Load a DataTable with an IDataReader that has extra columns:");
// Note that loading a reader with extra columns adds
// the columns to the existing table, if possible:
table = GetIntegerTable();
reader = new DataTableReader(GetCustomers());
table.Load(reader);
PrintColumns(table);
Console.WriteLine(" ============================= ");
Console.WriteLine(
"Load a DataTable with an IDataReader that has missing columns:");
// Note that loading a reader with missing columns causes
// the columns to be filled with null data, if possible:
table = GetCustomers();
reader = new DataTableReader(GetIntegerTable());
table.Load(reader);
PrintColumns(table);
// Demonstrate the various possibilites when loading data
// into a DataTable that already contains data.
Console.WriteLine(" ============================= ");
Console.WriteLine("Demonstrate data considerations:");
Console.WriteLine("Current value, Original value, (RowState)");
Console.WriteLine(" ============================= ");
Console.WriteLine("Original table:");
table = SetupModifiedRows();
DisplayRowState(table);
Console.WriteLine(" ============================= ");
Console.WriteLine("Data in IDataReader to be loaded:");
DisplayRowState(GetChangedCustomers());
// Load data into a DataTable, retrieve a DataTableReader
// containing different data, and call the Load method.
Console.WriteLine(" ============================= ");
Console.WriteLine("table.Load(reader)");
Console.WriteLine(" ============================= ");
table = SetupModifiedRows();
reader = new DataTableReader(GetChangedCustomers());
table.Load(reader);
DisplayRowState(table);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static void DisplayRowState(DataTable table)
{
for (int i = 0; i <= table.Rows.Count - 1; i++)
{
object current = "--";
object original = "--";
DataRowState rowState = table.Rows[i].RowState;
// Attempt to retrieve the current value, which doesn't exist
// for deleted rows:
if (rowState != DataRowState.Deleted)
{
current = table.Rows[i]["Name", DataRowVersion.Current];
}
// Attempt to retrieve the original value, which doesn't exist
// for added rows:
if (rowState != DataRowState.Added)
{
original = table.Rows[i]["Name", DataRowVersion.Original];
}
Console.WriteLine("{0}: {1}, {2} ({3})", i,
current, original, rowState);
}
}
private static DataTable GetChangedCustomers()
{
// Create sample Customers table.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID",
typeof(int));
table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 1, "XXX" });
table.Rows.Add(new object[] { 2, "XXX" });
table.Rows.Add(new object[] { 3, "XXX" });
table.Rows.Add(new object[] { 4, "XXX" });
table.Rows.Add(new object[] { 5, "XXX" });
table.Rows.Add(new object[] { 6, "XXX" });
table.AcceptChanges();
return table;
}
private static DataTable GetCustomers()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID",
typeof(int));
table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 1, "Mary" });
table.Rows.Add(new object[] { 2, "Andy" });
table.Rows.Add(new object[] { 3, "Peter" });
table.Rows.Add(new object[] { 4, "Russ" });
table.AcceptChanges();
return table;
}
private static DataTable GetIntegerTable()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID",
typeof(int));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 5 });
table.Rows.Add(new object[] { 6 });
table.Rows.Add(new object[] { 7 });
table.Rows.Add(new object[] { 8 });
table.AcceptChanges();
return table;
}
private static DataTable GetStringTable()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID",
typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { "Mary" });
table.Rows.Add(new object[] { "Andy" });
table.Rows.Add(new object[] { "Peter" });
table.Rows.Add(new object[] { "Russ" });
table.AcceptChanges();
return table;
}
private static void PrintColumns(DataTable table)
{
// Loop through all the rows in the DataTableReader
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
Console.Write(row[i] + " ");
}
Console.WriteLine();
}
}
private static DataTable SetupModifiedRows()
{
// Fill a DataTable with customer info, and
// then modify, delete, and add rows.
DataTable table = GetCustomers();
// Row 0 is unmodified.
// Row 1 is modified.
// Row 2 is deleted.
// Row 5 is added.
table.Rows[1]["Name"] = "Sydney";
table.Rows[2].Delete();
DataRow row = table.NewRow();
row["ID"] = 5;
row["Name"] = "Melony";
table.Rows.Add(row);
// Note that the code doesn't call
// table.AcceptChanges()
return table;
}
Sub Main()
' This example examines a number of scenarios involving the
' DataTable.Load method.
Console.WriteLine("Load a DataTable and infer its schema:")
' The table has no schema. The Load method will infer the
' schema from the IDataReader:
Dim table As New DataTable()
' Retrieve a data reader, based on the Customers data. In
' an application, this data might be coming from a middle-tier
' business object:
Dim reader As New DataTableReader(GetCustomers())
table.Load(reader)
PrintColumns(table)
Console.WriteLine(" ============================= ")
Console.WriteLine( _
"Load a DataTable from an incompatible IDataReader:")
' Create a table with a single integer column. Attempt
' to load data from a reader with a schema that is
' incompatible. Note the exception, determined
' by the particular incompatibility:
table = GetIntegerTable()
reader = New DataTableReader(GetStringTable())
Try
table.Load(reader)
Catch ex As Exception
Console.WriteLine(ex.GetType.Name & ":" & ex.Message())
End Try
Console.WriteLine(" ============================= ")
Console.WriteLine( _
"Load a DataTable with an IDataReader that has extra columns:")
' Note that loading a reader with extra columns adds
' the columns to the existing table, if possible:
table = GetIntegerTable()
reader = New DataTableReader(GetCustomers())
table.Load(reader)
PrintColumns(table)
Console.WriteLine(" ============================= ")
Console.WriteLine( _
"Load a DataTable with an IDataReader that has missing columns:")
' Note that loading a reader with missing columns causes
' the columns to be filled with null data, if possible:
table = GetCustomers()
reader = New DataTableReader(GetIntegerTable())
table.Load(reader)
PrintColumns(table)
' Demonstrate the various possibilites when loading data into
' a DataTable that already contains data.
Console.WriteLine(" ============================= ")
Console.WriteLine("Demonstrate data considerations:")
Console.WriteLine("Current value, Original value, (RowState)")
Console.WriteLine(" ============================= ")
Console.WriteLine("Original table:")
table = SetupModifiedRows()
DisplayRowState(table)
Console.WriteLine(" ============================= ")
Console.WriteLine("Data in IDataReader to be loaded:")
DisplayRowState(GetChangedCustomers())
' Load data into a DataTable, retrieve a DataTableReader
' containing different data, and call the Load method.
Console.WriteLine(" ============================= ")
Console.WriteLine("table.Load(reader)")
Console.WriteLine(" ============================= ")
table = SetupModifiedRows()
reader = New DataTableReader(GetChangedCustomers())
table.Load(reader)
DisplayRowState(table)
Console.WriteLine("Press any key to continue.")
Console.ReadKey()
End Sub
Private Sub DisplayRowState(ByVal table As DataTable)
For i As Integer = 0 To table.Rows.Count - 1
Dim current As Object = "--"
Dim original As Object = "--"
Dim rowState As DataRowState = table.Rows(i).RowState
' Attempt to retrieve the current value, which doesn't exist
' for deleted rows:
If rowState <> DataRowState.Deleted Then
current = table.Rows(i)("Name", DataRowVersion.Current)
End If
' Attempt to retrieve the original value, which doesn't exist
' for added rows:
If rowState <> DataRowState.Added Then
original = table.Rows(i)("Name", DataRowVersion.Original)
End If
Console.WriteLine("{0}: {1}, {2} ({3})", i, _
current, original, rowState)
Next
End Sub
Private Function GetChangedCustomers() As DataTable
' Create sample Customers table.
Dim table As New DataTable
' Create two columns, ID and Name.
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(Integer))
table.Columns.Add("Name", GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {1, "XXX"})
table.Rows.Add(New Object() {2, "XXX"})
table.Rows.Add(New Object() {3, "XXX"})
table.Rows.Add(New Object() {4, "XXX"})
table.Rows.Add(New Object() {5, "XXX"})
table.Rows.Add(New Object() {6, "XXX"})
table.AcceptChanges()
Return table
End Function
Private Function GetCustomers() As DataTable
' Create sample Customers table.
Dim table As New DataTable
' Create two columns, ID and Name.
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(Integer))
table.Columns.Add("Name", GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {1, "Mary"})
table.Rows.Add(New Object() {2, "Andy"})
table.Rows.Add(New Object() {3, "Peter"})
table.Rows.Add(New Object() {4, "Russ"})
table.AcceptChanges()
Return table
End Function
Private Function GetIntegerTable() As DataTable
' Create sample table with a single Int32 column.
Dim table As New DataTable
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(Integer))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {5})
table.Rows.Add(New Object() {6})
table.Rows.Add(New Object() {7})
table.Rows.Add(New Object() {8})
table.AcceptChanges()
Return table
End Function
Private Function GetStringTable() As DataTable
' Create sample table with a single String column.
Dim table As New DataTable
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {"Mary"})
table.Rows.Add(New Object() {"Andy"})
table.Rows.Add(New Object() {"Peter"})
table.Rows.Add(New Object() {"Russ"})
table.AcceptChanges()
Return table
End Function
Private Sub PrintColumns( _
ByVal table As DataTable)
' Loop through all the rows in the DataTableReader.
For Each row As DataRow In table.Rows
For Each col As DataColumn In table.Columns
Console.Write(row(col).ToString() & " ")
Next
Console.WriteLine()
Next
End Sub
Private Function SetupModifiedRows() As DataTable
' Fill a DataTable with customer info, and
' then modify, delete, and add rows.
Dim table As DataTable = GetCustomers()
' Row 0 is unmodified.
' Row 1 is modified.
' Row 2 is deleted.
' Row 5 is added.
table.Rows(1)("Name") = "Sydney"
table.Rows(2).Delete()
Dim row As DataRow = table.NewRow
row("ID") = 5
row("Name") = "Melony"
table.Rows.Add(row)
' Note that the code doesn't call
' table.AcceptChanges()
Return table
End Function
Observações
O Load método consome o primeiro conjunto de resultados do conjunto carregado IDataReadere, após a conclusão bem-sucedida, define a posição do leitor para o próximo conjunto de resultados, se existir. Ao converter dados, o Load método utiliza as mesmas regras de conversão que o DbDataAdapter.Fill método.
O Load método deve ter em conta três questões específicas ao carregar os dados de uma IDataReader instância: esquema, operações de dados e eventos. Ao trabalhar com o esquema, o Load método pode encontrar condições descritas na tabela seguinte. As operações de esquema ocorrem para todos os conjuntos de resultados importados, mesmo aqueles que não contêm dados.
| Condition | Comportamento |
|---|---|
| Não DataTable tem esquema. | O Load método infere o esquema com base no conjunto de resultados do .IDataReader |
| Tem DataTable um esquema, mas é incompatível com o esquema carregado. | O Load método lança uma exceção correspondente ao erro particular que ocorre ao tentar carregar dados no esquema incompatível. |
| Os esquemas são compatíveis, mas o esquema do conjunto de resultados carregado contém colunas que não existem no DataTable. | O Load método adiciona as colunas extra ao DataTableesquema de . O método lança uma exceção se as colunas correspondentes em e DataTable o conjunto de resultados carregados não forem compatíveis com valores. O método também recupera informação de restrições do conjunto de resultados para todas as colunas adicionadas. Exceto no caso da restrição de Chave Primária, esta informação de restrição é usada apenas se a corrente DataTable não contiver colunas no início da operação de carga. |
Os esquemas são compatíveis, mas o esquema do conjunto de resultados carregado contém menos colunas do que o DataTable. |
Se uma coluna em falta tiver um valor por defeito definido ou se o tipo de dado da coluna for anulável, o Load método permite que as linhas sejam adicionadas, substituindo a coluna em falta pelo valor padrão ou null valor. Se não for possível usar valor padrão, null então o Load método lança uma exceção. Se não tiver sido fornecido um valor padrão específico, o Load método usa esse null valor como valor implicito. |
Antes de considerar o comportamento do Load método em termos de operações de dados, considere que cada linha dentro de a DataTable mantém tanto o valor atual como o valor original para cada coluna. Estes valores podem ser equivalentes, ou podem ser diferentes se os dados na linha foram alterados desde o preenchimento do DataTable. Para mais informações, consulte Estados das Linhas e Versões das Linhas.
Esta versão do Load método tenta preservar os valores atuais em cada linha, mantendo o valor original intacto. (Se quiser um controlo mais fino sobre o comportamento dos dados recebidos, veja DataTable.Load.) Se a linha existente e a linha de entrada conterem valores de chave primária correspondentes, a linha é processada usando o seu valor atual de estado da linha, caso contrário é tratada como uma nova linha.
Em termos de operações de evento, o RowChanging evento ocorre antes de cada linha ser alterada, e ocorre RowChanged depois de cada linha ter sido alterada. Em cada caso, a Action propriedade da DataRowChangeEventArgs instância passada ao gestor de eventos contém informação sobre a ação particular associada ao evento. Este valor de ação depende do estado da linha antes da operação de carga. Em cada caso, ambos os eventos ocorrem, e a ação é a mesma para cada um. A ação pode ser aplicada à versão atual ou original de cada linha, ou a ambas, dependendo do estado da linha atual.
A tabela seguinte mostra o comportamento do Load método. A última linha (rotulada como "(Não presente)") descreve o comportamento das linhas que chegam e que não correspondem a nenhuma linha existente. Cada célula desta tabela descreve o valor atual e original de um campo dentro de uma linha, juntamente com o DataRowState valor após a conclusão do Load método. Neste caso, o método não permite indicar a opção de carregamento e usa o padrão, PreserveChanges.
| DataRowState Existente | Valores após Load o método e ação do evento |
|---|---|
| Adicionado | Atual = <Existente> Original = <Entrada> Estado = <Modificado> RowAction = AlteraçãoOriginal |
| Modificado | Atual = <Existente> Original = <Entrada> Estado = <Modificado> RowAction = AlteraçãoOriginal |
| Eliminados | Atual = <Não disponível> Original = <Entrada> Estado = <Eliminado> RowAction = AlteraçãoOriginal |
| Inalterado | Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
| (Não presente) | Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Os valores em a DataColumn podem ser restringidos através do uso de propriedades como ReadOnly e AutoIncrement. O Load método lida com tais colunas de forma consistente com o comportamento definido pelas propriedades da coluna. A restrição de apenas leitura em a DataColumn aplica-se apenas a alterações que ocorrem na memória. O Load método sobrescreve os valores das colunas só de leitura, se necessário.
Para determinar qual a versão do campo da chave primária usar para comparar a linha atual com a linha de entrada, o Load método usa a versão original do valor da chave primária dentro de uma linha, caso exista. Caso contrário, o Load método utiliza a versão atual do campo da chave primária.
Ver também
Aplica-se a
Load(IDataReader, LoadOption)
Preenche a DataTable com valores de uma fonte de dados usando o .IDataReader Se já DataTable contiver linhas, os dados recebidos da fonte de dados são fundidos com as linhas existentes de acordo com o valor do loadOption parâmetro.
public:
void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption);
public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption);
member this.Load : System.Data.IDataReader * System.Data.LoadOption -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption)
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 são DataTable combinadas com as linhas de entrada que partilham a mesma chave primária.
Exemplos
O exemplo seguinte demonstra várias das questões envolvidas em chamar o Load método. Primeiro, o exemplo foca-se em questões de esquema, incluindo inferir um esquema a partir do carregamento IDataReader, e depois tratar esquemas incompatíveis e esquemas com colunas em falta ou adicionais. O exemplo foca-se então em questões de dados, incluindo a gestão das várias opções de carregamento.
static void Main()
{
// This example examines a number of scenarios involving the
// DataTable.Load method.
Console.WriteLine("Load a DataTable and infer its schema:");
// The table has no schema. The Load method will infer the
// schema from the IDataReader:
DataTable table = new DataTable();
// Retrieve a data reader, based on the Customers data. In
// an application, this data might be coming from a middle-tier
// business object:
DataTableReader reader = new DataTableReader(GetCustomers());
table.Load(reader);
PrintColumns(table);
Console.WriteLine(" ============================= ");
Console.WriteLine(
"Load a DataTable from an incompatible IDataReader:");
// Create a table with a single integer column. Attempt
// to load data from a reader with a schema that is
// incompatible. Note the exception, determined
// by the particular incompatibility:
table = GetIntegerTable();
reader = new DataTableReader(GetStringTable());
try
{
table.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ":" + ex.Message);
}
Console.WriteLine(" ============================= ");
Console.WriteLine(
"Load a DataTable with an IDataReader that has extra columns:");
// Note that loading a reader with extra columns adds
// the columns to the existing table, if possible:
table = GetIntegerTable();
reader = new DataTableReader(GetCustomers());
table.Load(reader);
PrintColumns(table);
Console.WriteLine(" ============================= ");
Console.WriteLine(
"Load a DataTable with an IDataReader that has missing columns:");
// Note that loading a reader with missing columns causes
// the columns to be filled with null data, if possible:
table = GetCustomers();
reader = new DataTableReader(GetIntegerTable());
table.Load(reader);
PrintColumns(table);
// Demonstrate the various possibilites when loading data into
// a DataTable that already contains data.
Console.WriteLine(" ============================= ");
Console.WriteLine("Demonstrate data considerations:");
Console.WriteLine("Current value, Original value, (RowState)");
Console.WriteLine(" ============================= ");
Console.WriteLine("Original table:");
table = SetupModifiedRows();
DisplayRowState(table);
Console.WriteLine(" ============================= ");
Console.WriteLine("Data in IDataReader to be loaded:");
DisplayRowState(GetChangedCustomers());
PerformDemo(LoadOption.OverwriteChanges);
PerformDemo(LoadOption.PreserveChanges);
PerformDemo(LoadOption.Upsert);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static void DisplayRowState(DataTable table)
{
for (int i = 0; i <= table.Rows.Count - 1; i++)
{
object current = "--";
object original = "--";
DataRowState rowState = table.Rows[i].RowState;
// Attempt to retrieve the current value, which doesn't exist
// for deleted rows:
if (rowState != DataRowState.Deleted)
{
current = table.Rows[i]["Name", DataRowVersion.Current];
}
// Attempt to retrieve the original value, which doesn't exist
// for added rows:
if (rowState != DataRowState.Added)
{
original = table.Rows[i]["Name", DataRowVersion.Original];
}
Console.WriteLine("{0}: {1}, {2} ({3})", i,
current, original, rowState);
}
}
private static DataTable GetChangedCustomers()
{
// Create sample Customers table.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 0, "XXX" });
table.Rows.Add(new object[] { 1, "XXX" });
table.Rows.Add(new object[] { 2, "XXX" });
table.Rows.Add(new object[] { 3, "XXX" });
table.Rows.Add(new object[] { 4, "XXX" });
table.AcceptChanges();
return table;
}
private static DataTable GetCustomers()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 0, "Mary" });
table.Rows.Add(new object[] { 1, "Andy" });
table.Rows.Add(new object[] { 2, "Peter" });
table.AcceptChanges();
return table;
}
private static DataTable GetIntegerTable()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 4 });
table.Rows.Add(new object[] { 5 });
table.AcceptChanges();
return table;
}
private static DataTable GetStringTable()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { "Mary" });
table.Rows.Add(new object[] { "Andy" });
table.Rows.Add(new object[] { "Peter" });
table.AcceptChanges();
return table;
}
private static void PerformDemo(LoadOption optionForLoad)
{
// Load data into a DataTable, retrieve a DataTableReader containing
// different data, and call the Load method. Depending on the
// LoadOption value passed as a parameter, this procedure displays
// different results in the DataTable.
Console.WriteLine(" ============================= ");
Console.WriteLine("table.Load(reader, {0})", optionForLoad);
Console.WriteLine(" ============================= ");
DataTable table = SetupModifiedRows();
DataTableReader reader = new DataTableReader(GetChangedCustomers());
table.RowChanging +=new DataRowChangeEventHandler(HandleRowChanging);
table.Load(reader, optionForLoad);
Console.WriteLine();
DisplayRowState(table);
}
private static void PrintColumns(DataTable table)
{
// Loop through all the rows in the DataTableReader
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
Console.Write(row[i] + " ");
}
Console.WriteLine();
}
}
private static DataTable SetupModifiedRows()
{
// Fill a DataTable with customer info, and
// then modify, delete, and add rows.
DataTable table = GetCustomers();
// Row 0 is unmodified.
// Row 1 is modified.
// Row 2 is deleted.
// Row 3 is added.
table.Rows[1]["Name"] = "Sydney";
table.Rows[2].Delete();
DataRow row = table.NewRow();
row["ID"] = 3;
row["Name"] = "Melony";
table.Rows.Add(row);
// Note that the code doesn't call
// table.AcceptChanges()
return table;
}
static void HandleRowChanging(object sender, DataRowChangeEventArgs e)
{
Console.WriteLine(
"RowChanging event: ID = {0}, action = {1}", e.Row["ID"], e.Action);
}
Sub Main()
Dim table As New DataTable()
' This example examines a number of scenarios involving the
' DataTable.Load method.
Console.WriteLine("Load a DataTable and infer its schema:")
' Retrieve a data reader, based on the Customers data. In
' an application, this data might be coming from a middle-tier
' business object:
Dim reader As New DataTableReader(GetCustomers())
' The table has no schema. The Load method will infer the
' schema from the IDataReader:
table.Load(reader)
PrintColumns(table)
Console.WriteLine(" ============================= ")
Console.WriteLine( _
"Load a DataTable from an incompatible IDataReader:")
' Create a table with a single integer column. Attempt
' to load data from a reader with a schema that is
' incompatible. Note the exception, determined
' by the particular incompatibility:
table = GetIntegerTable()
reader = New DataTableReader(GetStringTable())
Try
table.Load(reader)
Catch ex As Exception
Console.WriteLine(ex.GetType.Name & ":" & ex.Message())
End Try
Console.WriteLine(" ============================= ")
Console.WriteLine( _
"Load a DataTable with an IDataReader that has extra columns:")
' Note that loading a reader with extra columns adds
' the columns to the existing table, if possible:
table = GetIntegerTable()
reader = New DataTableReader(GetCustomers())
table.Load(reader)
PrintColumns(table)
Console.WriteLine(" ============================= ")
Console.WriteLine( _
"Load a DataTable with an IDataReader that has missing columns:")
' Note that loading a reader with missing columns causes
' the columns to be filled with null data, if possible:
table = GetCustomers()
reader = New DataTableReader(GetIntegerTable())
table.Load(reader)
PrintColumns(table)
' Demonstrate the various possibilites when loading data into
' a DataTable that already contains data.
Console.WriteLine(" ============================= ")
Console.WriteLine("Demonstrate data considerations:")
Console.WriteLine("Current value, Original value, (RowState)")
Console.WriteLine(" ============================= ")
Console.WriteLine("Original table:")
table = SetupModifiedRows()
DisplayRowState(table)
Console.WriteLine(" ============================= ")
Console.WriteLine("Data in IDataReader to be loaded:")
DisplayRowState(GetChangedCustomers())
PerformDemo(LoadOption.OverwriteChanges)
PerformDemo(LoadOption.PreserveChanges)
PerformDemo(LoadOption.Upsert)
Console.WriteLine("Press any key to continue.")
Console.ReadKey()
End Sub
Private Sub DisplayRowState(ByVal table As DataTable)
For i As Integer = 0 To table.Rows.Count - 1
Dim current As Object = "--"
Dim original As Object = "--"
Dim rowState As DataRowState = table.Rows(i).RowState
' Attempt to retrieve the current value, which doesn't exist
' for deleted rows:
If rowState <> DataRowState.Deleted Then
current = table.Rows(i)("Name", DataRowVersion.Current)
End If
' Attempt to retrieve the original value, which doesn't exist
' for added rows:
If rowState <> DataRowState.Added Then
original = table.Rows(i)("Name", DataRowVersion.Original)
End If
Console.WriteLine("{0}: {1}, {2} ({3})", i, _
current, original, rowState)
Next
End Sub
Private Function GetChangedCustomers() As DataTable
' Create sample Customers table.
Dim table As New DataTable
' Create two columns, ID and Name.
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(Integer))
table.Columns.Add("Name", GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {0, "XXX"})
table.Rows.Add(New Object() {1, "XXX"})
table.Rows.Add(New Object() {2, "XXX"})
table.Rows.Add(New Object() {3, "XXX"})
table.Rows.Add(New Object() {4, "XXX"})
table.AcceptChanges()
Return table
End Function
Private Function GetCustomers() As DataTable
' Create sample Customers table.
Dim table As New DataTable
' Create two columns, ID and Name.
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(Integer))
table.Columns.Add("Name", GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {0, "Mary"})
table.Rows.Add(New Object() {1, "Andy"})
table.Rows.Add(New Object() {2, "Peter"})
table.AcceptChanges()
Return table
End Function
Private Function GetIntegerTable() As DataTable
' Create sample table with a single Int32 column.
Dim table As New DataTable
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(Integer))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {4})
table.Rows.Add(New Object() {5})
table.AcceptChanges()
Return table
End Function
Private Function GetStringTable() As DataTable
' Create sample table with a single String column.
Dim table As New DataTable
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {"Mary"})
table.Rows.Add(New Object() {"Andy"})
table.Rows.Add(New Object() {"Peter"})
table.AcceptChanges()
Return table
End Function
Private Sub PerformDemo(ByVal optionForLoad As LoadOption)
' Load data into a DataTable, retrieve a DataTableReader containing
' different data, and call the Load method. Depending on the
' LoadOption value passed as a parameter, this procedure displays
' different results in the DataTable.
Console.WriteLine(" ============================= ")
Console.WriteLine("table.Load(reader, {0})", optionForLoad)
Console.WriteLine(" ============================= ")
Dim table As DataTable = SetupModifiedRows()
Dim reader As New DataTableReader(GetChangedCustomers())
AddHandler table.RowChanging, New _
DataRowChangeEventHandler(AddressOf HandleRowChanging)
table.Load(reader, optionForLoad)
Console.WriteLine()
DisplayRowState(table)
End Sub
Private Sub PrintColumns( _
ByVal table As DataTable)
' Loop through all the rows in the DataTableReader.
For Each row As DataRow In table.Rows
For Each col As DataColumn In table.Columns
Console.Write(row(col).ToString() & " ")
Next
Console.WriteLine()
Next
End Sub
Private Function SetupModifiedRows() As DataTable
' Fill a DataTable with customer info, and
' then modify, delete, and add rows.
Dim table As DataTable = GetCustomers()
' Row 0 is unmodified.
' Row 1 is modified.
' Row 2 is deleted.
' Row 3 is added.
table.Rows(1)("Name") = "Sydney"
table.Rows(2).Delete()
Dim row As DataRow = table.NewRow
row("ID") = 3
row("Name") = "Melony"
table.Rows.Add(row)
' Note that the code doesn't call
' table.AcceptChanges()
Return table
End Function
Private Sub HandleRowChanging(ByVal sender As Object, _
ByVal e As System.Data.DataRowChangeEventArgs)
Console.WriteLine( _
"RowChanging event: ID = {0}, action = {1}", e.Row("ID"), e.Action)
End Sub
Observações
O Load método consome o primeiro conjunto de resultados do conjunto carregado IDataReadere, após a conclusão bem-sucedida, define a posição do leitor para o próximo conjunto de resultados, se existir. Ao converter dados, o Load método utiliza as mesmas regras de conversão que o Fill método.
O Load método deve ter em conta três questões específicas ao carregar os dados de uma IDataReader instância: esquema, operações de dados e eventos. Ao trabalhar com o esquema, o Load método pode encontrar condições descritas na tabela seguinte. As operações de esquema ocorrem para todos os conjuntos de resultados importados, mesmo aqueles que não contêm dados.
| Condition | Comportamento |
|---|---|
| Não DataTable tem esquema. | O Load método infere o esquema com base no conjunto de resultados do .IDataReader |
| Tem DataTable um esquema, mas é incompatível com o esquema carregado. | O Load método lança uma exceção correspondente ao erro particular que ocorre ao tentar carregar dados no esquema incompatível. |
Os esquemas são compatíveis, mas o esquema do conjunto de resultados carregado contém colunas que não existem no DataTablearquivo . |
O Load método adiciona as colunas extra ao DataTableesquema de . O método lança uma exceção se as colunas correspondentes em e DataTable o conjunto de resultados carregados não forem compatíveis com valores. O método também recupera informação de restrições do conjunto de resultados para todas as colunas adicionadas. Exceto no caso da restrição de Chave Primária, esta informação de restrição é usada apenas se a corrente DataTable não contiver colunas no início da operação de carga. |
Os esquemas são compatíveis, mas o esquema do conjunto de resultados carregado contém menos colunas do que o DataTable. |
Se uma coluna em falta tiver um valor por defeito definido ou o tipo de dado da coluna for anulável, o Load método permite que as linhas sejam adicionadas, substituindo o valor por defeito ou nulo pela coluna em falta. Se não for possível usar valor padrão ou nulo, o Load método lança uma exceção. Se não tiver sido fornecido um valor padrão específico, o Load método usa o valor nulo como valor implicito. |
Antes de considerar o comportamento do Load método em termos de operações de dados, considere que cada linha dentro de a DataTable mantém tanto o valor atual como o valor original para cada coluna. Estes valores podem ser equivalentes, ou podem ser diferentes se os dados na linha foram alterados desde o preenchimento do DataTable. Consulte os Estados da Linha e as Versões da Linha para mais informações.
Nesta chamada de método, o parâmetro especificado LoadOption influencia o processamento dos dados recebidos. Como deve o método Load lidar com linhas de carregamento que têm a mesma chave primária que as linhas existentes? Deveria modificar os valores atuais, os valores originais ou ambos? Estas questões, e outras, são controladas pelo loadOption parâmetro.
Se a linha existente e a linha de entrada conterem valores de chave primária correspondentes, a linha é processada usando o seu valor atual de estado da linha, caso contrário é tratada como uma nova linha.
Em termos de operações de evento, o RowChanging evento ocorre antes de cada linha ser alterada, e ocorre RowChanged depois de cada linha ter sido alterada. Em cada caso, a Action propriedade da DataRowChangeEventArgs instância passada ao gestor de eventos contém informação sobre a ação particular associada ao evento. Este valor de ação varia, dependendo do estado da linha antes da operação de carga. Em cada caso, ambos os eventos ocorrem, e a ação é a mesma para cada um. A ação pode ser aplicada à versão atual ou original de cada linha, ou a ambas, dependendo do estado da linha atual.
A tabela seguinte mostra o comportamento do método Load quando chamado com cada um dos LoadOption valores, e também mostra como os valores interagem com o estado da linha que está a ser carregada. A última linha (rotulada como "(Não presente)") descreve o comportamento das linhas que chegam e que não correspondem a nenhuma linha existente. Cada célula desta tabela descreve o valor atual e original de um campo dentro de uma linha, juntamente com o DataRowState valor após a conclusão do Load método.
| DataRowState Existente | Upsert | OverwriteChanges | PreserveChanges (Comportamento padrão) |
|---|---|---|---|
| Adicionado | Atual = <Entrada> Original = -<Não disponível> Estado = <Adicionado> RowAction = Mudança |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Existente> Original = <Entrada> Estado = <Modificado> RowAction = AlteraçãoOriginal |
| Modificado | Atual = <Entrada> Original = <Existente> Estado = <Modificado> RowAction = Mudança |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Existente> Original = <Entrada> Estado = <Modificado> RowAction =ChangeOriginal |
| Eliminados | (O carregamento não afeta as linhas eliminadas) Atual = --- Original = <Existente> Estado = <Eliminado> (Nova linha é adicionada com as seguintes características) Atual = <Entrada> Original = <Não disponível> Estado = <Adicionado> RowAction = Somar |
Desfazer apagar e Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Não disponível> Original = <Entrada> Estado = <Eliminado> RowAction = AlteraçãoOriginal |
| Inalterado | Atual = <Entrada> Original = <Existente> Se o novo valor for igual ao valor existente, então Estado = <Inalterado> RowAction = Nada Caso contrário Estado = <Modificado> RowAction = Mudança |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
| Não presente) | Atual = <Entrada> Original = <Não disponível> Estado = <Adicionado> RowAction = Somar |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Os valores em a DataColumn podem ser restringidos através do uso de propriedades como ReadOnly e AutoIncrement. O Load método lida com tais colunas de forma consistente com o comportamento definido pelas propriedades da coluna. A restrição de apenas leitura em a DataColumn aplica-se apenas a alterações que ocorrem na memória. O Load método sobrescreve os valores das colunas só de leitura, se necessário.
Se especificar as opções OverwriteChanges ou PreserveChanges ao chamar o Load método, então assume-se que os dados recebidos vêm da DataTablefonte de dados primária de , e o DataTable acompanha as alterações e pode propagá-las de volta para a fonte de dados. Se selecionar a opção Upsert, assume-se que os dados vêm de uma fonte secundária, como dados fornecidos por um componente de nível intermédio, possivelmente alterados por um utilizador. Neste caso, assume-se que a intenção é agregar dados de uma ou mais fontes de dados no DataTable, e depois talvez propagar os dados de volta para a fonte de dados primária. O LoadOption parâmetro é usado para determinar a versão específica da linha que será usada para a comparação da chave primária. A tabela abaixo fornece os detalhes.
| Opção de carga | Versão DataRow usada para comparação de chaves primárias |
|---|---|
OverwriteChanges |
Versão original, se existir, caso contrário Versão atual |
PreserveChanges |
Versão original, se existir, caso contrário Versão atual |
Upsert |
Versão atual, se existir, caso contrário Versão original |
Ver também
Aplica-se a
Load(IDataReader, LoadOption, FillErrorEventHandler)
Preenche a DataTable com valores de uma fonte de dados usando o fornecido IDataReader usando um delegado de gestão de erros.
public:
virtual void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, System::Data::FillErrorEventHandler ^ errorHandler);
public virtual void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler);
abstract member Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
Public Overridable Sub Load (reader As IDataReader, loadOption As LoadOption, errorHandler As FillErrorEventHandler)
Parâmetros
- reader
- IDataReader
A IDataReader que fornece um conjunto de resultados.
- loadOption
- LoadOption
Um valor da LoadOption enumeração que indica como as linhas já existentes são DataTable 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.
Exemplos
static void Main()
{
// Attempt to load data from a data reader in which
// the schema is incompatible with the current schema.
// If you use exception handling, you won't get the chance
// to examine each row, and each individual table,
// as the Load method progresses.
// By taking advantage of the FillErrorEventHandler delegate,
// you can interact with the Load process as an error occurs,
// attempting to fix the problem, or simply continuing or quitting
// the Load process:
DataTable table = GetIntegerTable();
DataTableReader reader = new DataTableReader(GetStringTable());
table.Load(reader, LoadOption.OverwriteChanges, FillErrorHandler);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
private static DataTable GetIntegerTable()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 4 });
table.Rows.Add(new object[] { 5 });
table.AcceptChanges();
return table;
}
private static DataTable GetStringTable()
{
// Create sample Customers table, in order
// to demonstrate the behavior of the DataTableReader.
DataTable table = new DataTable();
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { "Mary" });
table.Rows.Add(new object[] { "Andy" });
table.Rows.Add(new object[] { "Peter" });
table.AcceptChanges();
return table;
}
static void FillErrorHandler(object sender, FillErrorEventArgs e)
{
// You can use the e.Errors value to determine exactly what
// went wrong.
if (e.Errors.GetType() == typeof(System.FormatException))
{
Console.WriteLine("Error when attempting to update the value: {0}",
e.Values[0]);
}
// Setting e.Continue to True tells the Load
// method to continue trying. Setting it to False
// indicates that an error has occurred, and the
// Load method raises the exception that got
// you here.
e.Continue = true;
}
Sub Main()
Dim table As New DataTable()
' Attempt to load data from a data reader in which
' the schema is incompatible with the current schema.
' If you use exception handling, you won't get the chance
' to examine each row, and each individual table,
' as the Load method progresses.
' By taking advantage of the FillErrorEventHandler delegate,
' you can interact with the Load process as an error occurs,
' attempting to fix the problem, or simply continuing or quitting
' the Load process:
table = GetIntegerTable()
Dim reader As New DataTableReader(GetStringTable())
table.Load(reader, LoadOption.OverwriteChanges, _
AddressOf FillErrorHandler)
Console.WriteLine("Press any key to continue.")
Console.ReadKey()
End Sub
Private Sub FillErrorHandler(ByVal sender As Object, _
ByVal e As FillErrorEventArgs)
' You can use the e.Errors value to determine exactly what
' went wrong.
If e.Errors.GetType Is GetType(System.FormatException) Then
Console.WriteLine("Error when attempting to update the value: {0}", _
e.Values(0))
End If
' Setting e.Continue to True tells the Load
' method to continue trying. Setting it to False
' indicates that an error has occurred, and the
' Load method raises the exception that got
' you here.
e.Continue = True
End Sub
Private Function GetIntegerTable() As DataTable
' Create sample table with a single Int32 column.
Dim table As New DataTable
Dim idColumn As DataColumn = table.Columns.Add("ID", GetType(Integer))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {4})
table.Rows.Add(New Object() {5})
table.TableName = "IntegerTable"
table.AcceptChanges()
Return table
End Function
Private Function GetStringTable() As DataTable
' Create sample table with a single String column.
Dim table As New DataTable
Dim idColumn As DataColumn = table.Columns.Add("ID", _
GetType(String))
' Set the ID column as the primary key column.
table.PrimaryKey = New DataColumn() {idColumn}
table.Rows.Add(New Object() {"Mary"})
table.Rows.Add(New Object() {"Andy"})
table.Rows.Add(New Object() {"Peter"})
table.AcceptChanges()
Return table
End Function
Private Sub PrintColumns( _
ByVal table As DataTable)
' Loop through all the rows in the DataTableReader.
For Each row As DataRow In table.Rows
For Each col As DataColumn In table.Columns
Console.Write(row(col).ToString() & " ")
Next
Console.WriteLine()
Next
End Sub
Observações
O Load método consome o primeiro conjunto de resultados do conjunto carregado IDataReadere, após a conclusão bem-sucedida, define a posição do leitor para o próximo conjunto de resultados, se existir. Ao converter dados, o Load método utiliza as mesmas regras de conversão que o DbDataAdapter.Fill método.
O Load método deve ter em conta três questões específicas ao carregar os dados de uma IDataReader instância: esquema, operações de dados e eventos. Ao trabalhar com o esquema, o Load método pode encontrar condições descritas na tabela seguinte. As operações de esquema ocorrem para todos os conjuntos de resultados importados, mesmo aqueles que não contêm dados.
| Condition | Comportamento |
|---|---|
| Não DataTable tem esquema. | O Load método infere o esquema com base no conjunto de resultados do .IDataReader |
| Tem DataTable um esquema, mas é incompatível com o esquema carregado. | O Load método lança uma exceção correspondente ao erro particular que ocorre ao tentar carregar dados no esquema incompatível. |
Os esquemas são compatíveis, mas o esquema do conjunto de resultados carregado contém colunas que não existem no DataTablearquivo . |
O Load método adiciona a(s) coluna(s) extra ao DataTableesquema de . O método lança uma exceção se as colunas correspondentes em e DataTable o conjunto de resultados carregados não forem compatíveis com valores. O método também recupera informação de restrições do conjunto de resultados para todas as colunas adicionadas. Exceto no caso da restrição de Chave Primária, esta informação de restrição é usada apenas se a corrente DataTable não contiver colunas no início da operação de carga. |
Os esquemas são compatíveis, mas o esquema do conjunto de resultados carregado contém menos colunas do que o DataTable. |
Se uma coluna em falta tiver um valor por defeito definido ou o tipo de dado da coluna for anulável, o Load método permite que as linhas sejam adicionadas, substituindo o valor por defeito ou nulo pela coluna em falta. Se não for possível usar valor padrão ou nulo, o Load método lança uma exceção. Se não tiver sido fornecido um valor padrão específico, o Load método usa o valor nulo como valor implicito. |
Antes de considerar o comportamento do Load método em termos de operações de dados, considere que cada linha dentro de a DataTable mantém tanto o valor atual como o valor original para cada coluna. Estes valores podem ser equivalentes, ou podem ser diferentes se os dados na linha foram alterados desde o preenchimento do DataTable. Consulte os Estados da Linha e as Versões da Linha para mais informações.
Nesta chamada de método, o parâmetro especificado LoadOption influencia o processamento dos dados recebidos. Como deve o método Load lidar com linhas de carregamento que têm a mesma chave primária que as linhas existentes? Deveria modificar os valores atuais, os valores originais ou ambos? Estas questões, e outras, são controladas pelo loadOption parâmetro.
Se a linha existente e a linha de entrada conterem valores de chave primária correspondentes, a linha é processada usando o seu valor atual de estado da linha, caso contrário é tratada como uma nova linha.
Em termos de operações de evento, o RowChanging evento ocorre antes de cada linha ser alterada, e ocorre RowChanged depois de cada linha ter sido alterada. Em cada caso, a Action propriedade da DataRowChangeEventArgs instância passada ao gestor de eventos contém informação sobre a ação particular associada ao evento. Este valor de ação varia, dependendo do estado da linha antes da operação de carga. Em cada caso, ambos os eventos ocorrem, e a ação é a mesma para cada um. A ação pode ser aplicada à versão atual ou original de cada linha, ou a ambas, dependendo do estado da linha atual.
A tabela seguinte mostra o comportamento do método Load quando chamado com cada um dos LoadOption valores, e também mostra como os valores interagem com o estado da linha que está a ser carregada. A última linha (rotulada como "(Não presente)") descreve o comportamento das linhas que chegam e que não correspondem a nenhuma linha existente. Cada célula desta tabela descreve o valor atual e original de um campo dentro de uma linha, juntamente com o DataRowState valor após a conclusão do Load método.
| DataRowState Existente | Upsert | OverwriteChanges | PreserveChanges (Comportamento padrão) |
|---|---|---|---|
| Adicionado | Atual = <Entrada> Original = -<Não disponível> Estado = <Adicionado> RowAction = Mudança |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Existente> Original = <Entrada> Estado = <Modificado> RowAction = AlteraçãoOriginal |
| Modificado | Atual = <Entrada> Original = <Existente> Estado = <Modificado> RowAction = Mudança |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Existente> Original = <Entrada> Estado = <Modificado> RowAction =ChangeOriginal |
| eleted | (O carregamento não afeta as linhas eliminadas) Atual = --- Original = <Existente> Estado = <Eliminado> (Nova linha é adicionada com as seguintes características) Atual = <Entrada> Original = <Não disponível> Estado = <Adicionado> RowAction = Somar |
Desfazer apagar e Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Não disponível> Original = <Entrada> Estado = <Eliminado> RowAction = AlteraçãoOriginal |
| Inalterado | Atual = <Entrada> Original = <Existente> Se o novo valor for igual ao valor existente, então Estado = <Inalterado> RowAction = Nada Caso contrário Estado = <Modificado> RowAction = Mudança |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
| Não presente) | Atual = <Entrada> Original = <Não disponível> Estado = <Adicionado> RowAction = Somar |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Atual = <Entrada> Original = <Entrada> Estado = <Inalterado> RowAction = ChangeCurrentAndOriginal |
Os valores em a DataColumn podem ser restringidos através do uso de propriedades como ReadOnly e AutoIncrement. O Load método lida com tais colunas de forma consistente com o comportamento definido pelas propriedades da coluna. A restrição de apenas leitura em a DataColumn aplica-se apenas a alterações que ocorrem na memória. O Load método sobrescreve os valores das colunas só de leitura, se necessário.
Se especificar as opções OverwriteChanges ou PreserveChanges ao chamar o Load método, então assume-se que os dados recebidos vêm da DataTablefonte de dados primária de , e o DataTable acompanha as alterações e pode propagá-las de volta para a fonte de dados. Se selecionar a opção Upsert, assume-se que os dados vêm de uma fonte secundária, como dados fornecidos por um componente de nível intermédio, possivelmente alterados por um utilizador. Neste caso, assume-se que a intenção é agregar dados de uma ou mais fontes de dados no DataTable, e depois talvez propagar os dados de volta para a fonte de dados primária. O LoadOption parâmetro é usado para determinar a versão específica da linha que será usada para a comparação da chave primária. A tabela abaixo fornece os detalhes.
| Opção de carga | Versão DataRow usada para comparação de chaves primárias |
|---|---|
OverwriteChanges |
Versão original, se existir, caso contrário Versão atual |
PreserveChanges |
Versão original, se existir, caso contrário Versão atual |
Upsert |
Versão atual, se existir, caso contrário Versão original |
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 interromper 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.