DataTable.Load DataTable.Load DataTable.Load DataTable.Load Method

Definición

Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada.Fills a DataTable with values from a data source using the supplied IDataReader. Si el objeto DataTable ya contiene filas, los datos de entrada del origen de datos se combinan con las filas existentes.If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows.

Sobrecargas

Load(IDataReader) Load(IDataReader) Load(IDataReader) Load(IDataReader)

Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada.Fills a DataTable with values from a data source using the supplied IDataReader. Si el objeto DataTable ya contiene filas, los datos de entrada del origen de datos se combinan con las filas existentes.If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows.

Load(IDataReader, LoadOption) Load(IDataReader, LoadOption) Load(IDataReader, LoadOption)

Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada.Fills a DataTable with values from a data source using the supplied IDataReader. Si el objeto DataTable ya contiene las filas, los datos de entrada del origen de datos se combinan con las filas existentes conforme al valor del parámetro loadOption.If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows according to the value of the loadOption parameter.

Load(IDataReader, LoadOption, FillErrorEventHandler) Load(IDataReader, LoadOption, FillErrorEventHandler) Load(IDataReader, LoadOption, FillErrorEventHandler)

Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada y un delegado de control de errores.Fills a DataTable with values from a data source using the supplied IDataReader using an error-handling delegate.

Ejemplos

El ejemplo siguiente muestra algunos de los aspectos necesarios para llamar a la Load método.The following example demonstrates several of the issues involved with calling the Load method. En primer lugar, el ejemplo se centra en los problemas de esquema, incluidos inferir un esquema de la carga IDataReadery, a continuación, controlar los esquemas incompatibles y esquemas con columnas adicionales o faltantes.First, the example focuses on schema issues, including inferring a schema from the loaded IDataReader, and then handling incompatible schemas, and schemas with missing or additional columns. En el ejemplo, a continuación, se centra en los problemas de datos, incluido el control de las distintas opciones de carga.The example then focuses on data issues, including handling the various loading options.

Nota

En este ejemplo se muestra cómo usar una de las versiones sobrecargadas de Load.This example shows how to use one of the overloaded versions of Load. Para obtener otros ejemplos, vea los temas individuales de sobrecarga.For other examples that might be available, see the individual overload topics.

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

Comentarios

El Load método puede utilizarse en varios escenarios comunes, todo en torno a la obtención de datos de un origen de datos especificado y lo agrega al contenedor de datos actual (en este caso, un DataTable).The Load method can be used in several common scenarios, all centered around getting data from a specified data source and adding it to the current data container (in this case, a DataTable). Estos escenarios describen el uso estándar para un DataTable, que describe su actualización y el comportamiento de combinación.These scenarios describe standard usage for a DataTable, describing its update and merge behavior.

Un DataTable sincroniza o actualiza con un origen de datos principal única.A DataTable synchronizes or updates with a single primary data source. El DataTable realiza el seguimiento de cambios, lo que permite la sincronización con el origen de datos principal.The DataTable tracks changes, allowing synchronization with the primary data source. Además, un DataTable puede aceptar datos incrementales de uno o varios orígenes de datos secundario.In addition, a DataTable can accept incremental data from one or more secondary data sources. El DataTable no es responsable del seguimiento de cambios con el fin de permitir la sincronización con el origen de datos secundario.The DataTable isn't responsible for tracking changes in order to allow synchronization with the secondary data source.

Dados estos dos orígenes de datos hipotética, un usuario es probable que se necesita uno de los comportamientos siguientes:Given these two hypothetical data sources, a user is likely to require one of the following behaviors:

  • Inicializar DataTable desde un origen de datos principal.Initialize DataTable from a primary data source. En este escenario, el usuario desea inicializar vacío DataTable con valores procedentes del origen de datos principal.In this scenario, the user wants to initialize an empty DataTable with values from the primary data source. Más adelante la intención del usuario propagar los cambios en el origen de datos principal.Later the user intends to propagate changes back to the primary data source.

  • Conservar los cambios realizados y volver a sincronizar desde el origen de datos principal.Preserve changes and re-synchronize from the primary data source. En este escenario, el usuario desea tomar el DataTable rellena en el escenario anterior y realizar una sincronización incremental con el origen de datos principal, conservando las modificaciones realizadas en el DataTable.In this scenario, the user wants to take the DataTable filled in the previous scenario and perform an incremental synchronization with the primary data source, preserving modifications made in the DataTable.

  • Fuente de datos incrementales desde orígenes de datos secundaria.Incremental data feed from secondary data sources. En este escenario, el usuario desea combinar los cambios de uno o varios orígenes de datos secundaria y propagar los cambios en el origen de datos principal.In this scenario, the user wants to merge changes from one or more secondary data sources, and propagate those changes back to the primary data source.

El Load método hace que todos estos escenarios posibles.The Load method makes all these scenarios possible. Todo menos una de las sobrecargas de este método permite especificar un parámetro de opción de carga, que indica cómo las filas ya está en un DataTable combinar con las filas que se está cargadas.All but one of the overloads for this method allows you to specify a load option parameter, indicating how rows already in a DataTable combine with rows being loaded. (La sobrecarga que no permite especificar el comportamiento utiliza la opción de carga de forma predeterminada). En la tabla siguiente se describe las opciones de tres carga proporcionadas por el LoadOption enumeración.(The overload that doesn't allow you to specify the behavior uses the default load option.) The following table describes the three load options provided by the LoadOption enumeration. En cada caso, la descripción indica el comportamiento cuando la clave principal de una fila en los datos de entrada coincide con la clave principal de una fila existente.In each case, the description indicates the behavior when the primary key of a row in the incoming data matches the primary key of an existing row.

Opción de cargaLoad Option DescripciónDescription
PreserveChanges (valor predeterminado)PreserveChanges (default) Actualiza la versión original de la fila con el valor de la fila entrante.Updates the original version of the row with the value of the incoming row.
OverwriteChanges Actualiza las versiones actuales y originales de la fila con el valor de la fila entrante.Updates the current and original versions of the row with the value of the incoming row.
Upsert Actualiza la versión actual de la fila con el valor de la fila entrante.Updates the current version of the row with the value of the incoming row.

En general, el PreserveChanges y OverwriteChanges opciones están pensadas para escenarios en los que el usuario necesita para sincronizar el DataSet y sus cambios con el origen de datos principal.In general, the PreserveChanges and OverwriteChanges options are intended for scenarios in which the user needs to synchronize the DataSet and its changes with the primary data source. El Upsert opción facilita la adición de cambios desde uno o varios orígenes de datos secundario.The Upsert option facilitates aggregating changes from one or more secondary data sources.

Load(IDataReader) Load(IDataReader) Load(IDataReader) Load(IDataReader)

Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada.Fills a DataTable with values from a data source using the supplied IDataReader. Si el objeto DataTable ya contiene filas, los datos de entrada del origen de datos se combinan con las filas existentes.If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows.

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 IDataReader IDataReader IDataReader

Interfaz IDataReader que proporciona un conjunto de resultados.An IDataReader that provides a result set.

Ejemplos

El ejemplo siguiente muestra algunos de los aspectos necesarios para llamar a la Load método.The following example demonstrates several of the issues involved with calling the Load method. En primer lugar, el ejemplo se centra en los problemas de esquema, incluidos inferir un esquema de la carga IDataReadery, a continuación, controlar los esquemas incompatibles y esquemas con columnas adicionales o faltantes.First, the example focuses on schema issues, including inferring a schema from the loaded IDataReader, and then handling incompatible schemas, and schemas with missing or additional columns. El ejemplo llama a la Load método, mostrar los datos antes y después de la operación de carga.The example then calls the Load method, displaying the data both before and after the load operation.

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

Comentarios

El Load método consume el primer conjunto de resultados de la carga IDataReadery tras finalizar correctamente, Establece la posición del lector hasta el siguiente conjunto de resultados, si hay alguno.The Load method consumes the first result set from the loaded IDataReader, and after successful completion, sets the reader's position to the next result set, if any. Al convertir los datos, el Load método usa las mismas reglas de conversión que el DbDataAdapter.Fill método.When converting data, the Load method uses the same conversion rules as the DbDataAdapter.Fill method.

El Load método debe tener en cuenta tres aspectos concretos al cargar los datos desde un IDataReader instancia: operaciones de esquema, datos y eventos.The Load method must take into account three specific issues when loading the data from an IDataReader instance: schema, data, and event operations. Cuando se trabaja con el esquema, el Load método puede encontrar las condiciones como se describe en la tabla siguiente.When working with the schema, the Load method may encounter conditions as described in the following table. Las operaciones de esquema tienen lugar para todos los conjuntos de resultados importados, incluso aquellos que no contienen datos.The schema operations take place for all imported result sets, even those containing no data.

CondiciónCondition ComportamientoBehavior
El DataTable no tiene un esquema.The DataTable has no schema. El Load método deduce el esquema según el conjunto de resultados de la información importada IDataReader.The Load method infers the schema based on the result set from the imported IDataReader.
El DataTable tiene un esquema, pero no es compatible con el esquema cargado.The DataTable has a schema, but it is incompatible with the loaded schema. El Load método produce una excepción correspondiente al error concreto que se produce al intentar cargar datos en el esquema incompatible.The Load method throws an exception corresponding to the particular error that occurs when attempting to load data into the incompatible schema.
Los esquemas son compatibles, pero el esquema del conjunto de resultados cargado contiene columnas que no existen en el DataTable.The schemas are compatible, but the loaded result set schema contains columns that do not exist in the DataTable. El Load método agrega las columnas adicionales para DataTabledel esquema.The Load method adds the extra columns to DataTable's schema. El método produce una excepción si correspondientes columnas de la DataTable y el conjunto de resultados cargado no tienen valores compatibles.The method throws an exception if corresponding columns in the DataTable and the loaded result set are not value compatible. El método también recupera información de restricciones de conjunto de resultados de todas las columnas agregadas.The method also retrieves constraint information from the result set for all added columns. Excepto en el caso de una restricción Primary Key, se usa la información de esta restricción solo si actual DataTable no contiene ninguna columna al principio de la operación de carga.Except for the case of Primary Key constraint, this constraint information is used only if the current DataTable does not contain any columns at the start of the load operation.
Los esquemas son compatibles, pero el esquema del conjunto de resultados cargado contiene menos columnas que el DataTable.The schemas are compatible, but the loaded result set schema contains fewer columns than does the DataTable. Si falta una columna con un valor predeterminado definido o tipo de datos de la columna admite valores NULL, el Load método permite que las filas que se va a agregarse, sustituyendo el valor predeterminado o null valor para la columna que faltan.If a missing column has a default value defined or the column's data type is nullable, the Load method allows the rows to be added, substituting the default or null value for the missing column. Si no tiene valor predeterminado o null puede usarse el Load método produce una excepción.If no default value or null can be used, then the Load method throws an exception. Si no se ha proporcionado ningún valor predeterminado concreto, el Load método usa la null valor como valor predeterminado implícito.If no specific default value has been supplied, the Load method uses the null value as the implied default value.

Antes de considerar el comportamiento de la Load método en cuanto a operaciones de datos, considere la posibilidad de que cada fila dentro de un DataTable mantiene el valor actual y el valor original de cada columna.Before considering the behavior of the Load method in terms of data operations, consider that each row within a DataTable maintains both the current value and the original value for each column. Estos valores pueden ser equivalentes, o puede ser diferentes si los datos de la fila ha cambiado desde llene la DataTable.These values may be equivalent, or may be different if the data in the row has been changed since filling the DataTable. Para obtener más información, consulte Estados de fila y las versiones de fila.For more information, see Row States and Row Versions.

Esta versión de la Load método intenta conservar los valores actuales de cada fila, dejando intacto el valor original.This version of the Load method attempts to preserve the current values in each row, leaving the original value intact. (Si desea un control más preciso sobre el comportamiento de los datos entrantes, vea DataTable.Load.) Si la fila existente y la fila entrante contienen valores de clave principal correspondientes, la fila se procesa mediante su valor de estado de fila actual, en caso contrario, se trata como una nueva fila.(If you want finer control over the behavior of incoming data, see DataTable.Load.) If the existing row and the incoming row contain corresponding primary key values, the row is processed using its current row state value, otherwise it's treated as a new row.

En cuanto a operaciones de evento, el RowChanging evento tiene lugar antes de que cambie cada fila y el RowChanged evento se produce después de cada fila ha cambiado.In terms of event operations, the RowChanging event occurs before each row is changed, and the RowChanged event occurs after each row has been changed. En cada caso, el Action propiedad de la DataRowChangeEventArgs instancia que se pasa al controlador de eventos contiene información acerca de la acción concreta asociada al evento.In each case, the Action property of the DataRowChangeEventArgs instance passed to the event handler contains information about the particular action associated with the event. Este valor de acción depende del estado de la fila antes de la operación de carga.This action value depends on the state of the row before the load operation. En cada caso, se produzcan ambos eventos y la acción es la misma para cada uno.In each case, both events occur, and the action is the same for each. La acción se puede aplicar a la versión actual o original de cada fila, o ambas, según el estado de la fila actual.The action may be applied to either the current or original version of each row, or both, depending on the current row state.

En la tabla siguiente muestra el comportamiento del Load método.The following table displays behavior for the Load method. La fila final (con la etiqueta "(no está presente)") describe el comportamiento de las filas entrantes que no coincide con ninguna fila existente.The final row (labeled "(Not present)") describes the behavior for incoming rows that don't match any existing row. Cada celda de esta tabla describe el valor actual y original de un campo dentro de una fila, junto con el DataRowState para el valor después de la Load método ha finalizado.Each cell in this table describes the current and original value for a field within a row, along with the DataRowState for the value after the Load method has completed. En este caso, el método no permite indicar que la opción de carga y utiliza el valor predeterminado, PreserveChanges.In this case, the method doesn't allow you to indicate the load option, and uses the default, PreserveChanges.

DataRowState existenteExisting DataRowState Los valores después de Load método y acción de eventoValues after Load method, and event action
AgregadoAdded Actual = <existente >Current = <Existing>

Original = <entrantes >Original = <Incoming>

Estado = <modificado >State = <Modified>

RowAction = ChangeOriginalRowAction = ChangeOriginal
ModifiedModified Actual = <existente >Current = <Existing>

Original = <entrantes >Original = <Incoming>

Estado = <modificado >State = <Modified>

RowAction = ChangeOriginalRowAction = ChangeOriginal
DeletedDeleted Actual = <no disponible >Current = <Not available>

Original = <entrantes >Original = <Incoming>

Estado = <eliminó >State = <Deleted>

RowAction = ChangeOriginalRowAction = ChangeOriginal
Sin cambiosUnchanged Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
(No está presente)(Not present) Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal

Los valores en un DataColumn puede restringirse mediante el uso de propiedades, como ReadOnly y AutoIncrement.Values in a DataColumn can be constrained through use of properties such as ReadOnly and AutoIncrement. El Load método controla estas columnas de una manera coherente con el comportamiento definido por las propiedades de la columna.The Load method handles such columns in a manner that is consistent with the behavior defined by the column's properties. La restricción de sólo lectura en un DataColumn sólo es aplicable para los cambios producidos en la memoria.The read only constraint on a DataColumn is applicable only for changes that occur in memory. El Load método sobrescribe los valores de columna de sólo lectura, si es necesario.The Load method's overwrites the read-only column values, if needed.

Para determinar qué versión del campo de clave principal que se utilizará para comparar la fila actual con una fila de entrada, el Load método usa la versión original del valor de clave principal en una fila, si existe.To determine which version of the primary key field to use for comparing the current row with an incoming row, the Load method uses the original version of the primary key value within a row, if it exists. En caso contrario, el Load método usa la versión actual del campo de clave principal.Otherwise, the Load method uses the current version of the primary key field.

Consulte también:

Load(IDataReader, LoadOption) Load(IDataReader, LoadOption) Load(IDataReader, LoadOption)

Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada.Fills a DataTable with values from a data source using the supplied IDataReader. Si el objeto DataTable ya contiene las filas, los datos de entrada del origen de datos se combinan con las filas existentes conforme al valor del parámetro loadOption.If the DataTable already contains rows, the incoming data from the data source is merged with the existing rows according to the value of the loadOption parameter.

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

Parámetros

reader
IDataReader IDataReader IDataReader IDataReader

IDataReader que proporciona uno o varios conjuntos de resultados.An IDataReader that provides one or more result sets.

loadOption
LoadOption LoadOption LoadOption LoadOption

Valor de la enumeración LoadOption que indica cómo se combinan las filas que ya existen en el objeto DataTable con las filas de entrada con las que comparten la misma clave principal.A value from the LoadOption enumeration that indicates how rows already in the DataTable are combined with incoming rows that share the same primary key.

Ejemplos

El ejemplo siguiente muestra algunos de los aspectos necesarios para llamar a la Load método.The following example demonstrates several of the issues involved with calling the Load method. En primer lugar, el ejemplo se centra en los problemas de esquema, incluidos inferir un esquema de la carga IDataReadery, a continuación, controlar los esquemas incompatibles y esquemas con columnas adicionales o faltantes.First, the example focuses on schema issues, including inferring a schema from the loaded IDataReader, and then handling incompatible schemas, and schemas with missing or additional columns. En el ejemplo, a continuación, se centra en los problemas de datos, incluido el control de las distintas opciones de carga.The example then focuses on data issues, including handling the various loading options.

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

Comentarios

El Load método consume el primer conjunto de resultados de la carga IDataReadery tras finalizar correctamente, Establece la posición del lector hasta el siguiente conjunto de resultados, si hay alguno.The Load method consumes the first result set from the loaded IDataReader, and after successful completion, sets the reader's position to the next result set, if any. Al convertir los datos, el Load método usa las mismas reglas de conversión que el Fill método.When converting data, the Load method uses the same conversion rules as the Fill method.

El Load método debe tener en cuenta tres aspectos concretos al cargar los datos desde un IDataReader instancia: operaciones de esquema, datos y eventos.The Load method must take into account three specific issues when loading the data from an IDataReader instance: schema, data, and event operations. Cuando se trabaja con el esquema, el Load método puede encontrar las condiciones como se describe en la tabla siguiente.When working with the schema, the Load method may encounter conditions as described in the following table. Las operaciones de esquema tienen lugar para todos los conjuntos de resultados importados, incluso aquellos que no contienen datos.The schema operations take place for all imported result sets, even those containing no data.

CondiciónCondition ComportamientoBehavior
El DataTable no tiene un esquema.The DataTable has no schema. El Load método deduce el esquema según el conjunto de resultados de la información importada IDataReader.The Load method infers the schema based on the result set from the imported IDataReader.
El DataTable tiene un esquema, pero no es compatible con el esquema cargado.The DataTable has a schema, but it is incompatible with the loaded schema. El Load método produce una excepción correspondiente al error concreto que se produce al intentar cargar datos en el esquema incompatible.The Load method throws an exception corresponding to the particular error that occurs when attempting to load data into the incompatible schema.
Los esquemas son compatibles, pero el esquema del conjunto de resultados cargado contiene columnas que no existen en el DataTable.The schemas are compatible, but the loaded result set schema contains columns that don't exist in the DataTable. El Load método agrega las columnas adicionales para DataTabledel esquema.The Load method adds the extra columns to DataTable's schema. El método produce una excepción si correspondientes columnas de la DataTable y el conjunto de resultados cargado no tienen valores compatibles.The method throws an exception if corresponding columns in the DataTable and the loaded result set are not value compatible. El método también recupera información de restricciones de conjunto de resultados de todas las columnas agregadas.The method also retrieves constraint information from the result set for all added columns. Excepto en el caso de una restricción Primary Key, se usa la información de esta restricción solo si actual DataTable no contiene ninguna columna al principio de la operación de carga.Except for the case of Primary Key constraint, this constraint information is used only if the current DataTable does not contain any columns at the start of the load operation.
Los esquemas son compatibles, pero el esquema del conjunto de resultados cargado contiene menos columnas que el DataTable.The schemas are compatible, but the loaded result set schema contains fewer columns than does the DataTable. Si falta una columna con un valor predeterminado definido o tipo de datos de la columna admite valores NULL, el Load método permite que las filas que se va a agregarse, sustituyendo el valor predeterminado o null para la columna que faltan.If a missing column has a default value defined or the column's data type is nullable, the Load method allows the rows to be added, substituting the default or null value for the missing column. Si no puede utilizarse valor predeterminado o null, el Load método produce una excepción.If no default value or null can be used, then the Load method throws an exception. Si no se ha proporcionado ningún valor predeterminado concreto, el Load método utiliza el valor null como valor predeterminado implícito.If no specific default value has been supplied, the Load method uses the null value as the implied default value.

Antes de considerar el comportamiento de la Load método en cuanto a operaciones de datos, considere la posibilidad de que cada fila dentro de un DataTable mantiene el valor actual y el valor original de cada columna.Before considering the behavior of the Load method in terms of data operations, consider that each row within a DataTable maintains both the current value and the original value for each column. Estos valores pueden ser equivalentes, o puede ser diferentes si los datos de la fila ha cambiado desde llene la DataTable.These values may be equivalent, or may be different if the data in the row has been changed since filling the DataTable. Consulte Estados de fila y las versiones de fila para obtener más información.See Row States and Row Versions for more information.

En esta llamada de método especificada LoadOption parámetro influye en el procesamiento de los datos entrantes.In this method call, the specified LoadOption parameter influences the processing of the incoming data. ¿Cómo debe controlar el método de carga al cargar las filas que tienen la misma clave principal que las filas existentes?How should the Load method handle loading rows that have the same primary key as existing rows? ¿Debe modificar los valores actuales, los valores originales o ambos?Should it modify current values, original values, or both? Estos problemas entre otros, se controlan mediante el loadOption parámetro.These issues, and more, are controlled by the loadOption parameter.

Si la fila existente y la fila entrante contienen valores de clave principal correspondientes, la fila se procesa mediante su valor de estado de fila actual, en caso contrario, se trata como una nueva fila.If the existing row and the incoming row contain corresponding primary key values, the row is processed using its current row state value, otherwise it's treated as a new row.

En cuanto a operaciones de evento, el RowChanging evento tiene lugar antes de que cambie cada fila y el RowChanged evento se produce después de cada fila ha cambiado.In terms of event operations, the RowChanging event occurs before each row is changed, and the RowChanged event occurs after each row has been changed. En cada caso, el Action propiedad de la DataRowChangeEventArgs instancia que se pasa al controlador de eventos contiene información acerca de la acción concreta asociada al evento.In each case, the Action property of the DataRowChangeEventArgs instance passed to the event handler contains information about the particular action associated with the event. Este valor de acción varía según el estado de la fila antes de la operación de carga.This action value varies, depending on the state of the row before the load operation. En cada caso, se produzcan ambos eventos y la acción es la misma para cada uno.In each case, both events occur, and the action is the same for each. La acción se puede aplicar a la versión actual o original de cada fila, o ambas, según el estado de la fila actual.The action may be applied to either the current or original version of each row, or both, depending on the current row state.

En la tabla siguiente muestra el comportamiento del método Load cuando se llama con cada uno de los LoadOption valores y también se muestra cómo interactúan los valores con el estado de fila para la fila que se está cargando.The following table displays behavior for the Load method when called with each of the LoadOption values, and also shows how the values interact with the row state for the row being loaded. La fila final (con la etiqueta "(no está presente)") describe el comportamiento de las filas entrantes que no coincide con ninguna fila existente.The final row (labeled "(Not present)") describes the behavior for incoming rows that don't match any existing row. Cada celda de esta tabla describe el valor actual y original de un campo dentro de una fila, junto con el DataRowState para el valor después de la Load método ha finalizado.Each cell in this table describes the current and original value for a field within a row, along with the DataRowState for the value after the Load method has completed.

DataRowState existenteExisting DataRowState UpsertUpsert OverwriteChangesOverwriteChanges PreserveChanges (comportamiento predeterminado)PreserveChanges (Default behavior)
AgregadoAdded Actual = <entrantes >Current = <Incoming>

Original = -<no disponible >Original = -<Not available>

Estado = <agregado >State = <Added>

RowAction = cambioRowAction = Change
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <existente >Current = <Existing>

Original = <entrantes >Original = <Incoming>

Estado = <modificado >State = <Modified>

RowAction = ChangeOriginalRowAction = ChangeOriginal
ModifiedModified Actual = <entrantes >Current = <Incoming>

Original = <existente >Original = <Existing>

Estado = <modificado >State = <Modified>

RowAction = cambioRowAction = Change
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <existente >Current = <Existing>

Original = <entrantes >Original = <Incoming>

Estado = <modificado >State = <Modified>

RowAction = ChangeOriginalRowAction =ChangeOriginal
DeletedDeleted (La carga no no afectan a eliminar las filas)(Load does not affect deleted rows)

Actual =---Current = ---

Original = <existente >Original = <Existing>

Estado = <eliminó >State = <Deleted>

(Se agrega una fila nueva con las siguientes características)(New row is added with the following characteristics)

Actual = <entrantes >Current = <Incoming>

Original = <no disponible >Original = <Not available>

Estado = <agregado >State = <Added>

RowAction = agregarRowAction = Add
Deshacer la eliminación yUndo delete and

Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <no disponible >Current = <Not available>

Original = <entrantes >Original = <Incoming>

Estado = <eliminó >State = <Deleted>

RowAction = ChangeOriginalRowAction = ChangeOriginal
Sin cambiosUnchanged Actual = <entrantes >Current = <Incoming>

Original = <existente >Original = <Existing>

Si el nuevo valor es igual que el valor existente, a continuaciónIf new value is the same as the existing value then

Estado = <sin cambios >State = <Unchanged>

RowAction = NothingRowAction = Nothing

ElseElse

Estado = <modificado >State = <Modified>

RowAction = cambioRowAction = Change
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
No está presente)Not present) Actual = <entrantes >Current = <Incoming>

Original = <no disponible >Original = <Not available>

Estado = <agregado >State = <Added>

RowAction = agregarRowAction = Add
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal

Los valores en un DataColumn puede restringirse mediante el uso de propiedades, como ReadOnly y AutoIncrement.Values in a DataColumn can be constrained through use of properties such as ReadOnly and AutoIncrement. El Load método controla estas columnas de una manera coherente con el comportamiento definido por las propiedades de la columna.The Load method handles such columns in a manner that is consistent with the behavior defined by the column's properties. La restricción de sólo lectura en un DataColumn sólo es aplicable para los cambios producidos en la memoria.The read only constraint on a DataColumn is applicable only for changes that occur in memory. El Load método sobrescribe los valores de columna de sólo lectura, si es necesario.The Load method's overwrites the read-only column values, if needed.

Si especifica las opciones OverwriteChanges o PreserveChanges al llamar a la Load se realiza método y, a continuación, la suposición de que los datos de entrada procede de la DataTabledel origen de datos principal y la tabla de datos realiza un seguimiento de cambios y se pueden propagar los cambios en el origen de datos.If you specify the OverwriteChanges or PreserveChanges options when calling the Load method, then the assumption is made that the incoming data is coming from the DataTable's primary data source, and the DataTable tracks changes and can propagate the changes back to the data source. Si selecciona la opción Upsert, se supone que los datos proceden de uno de un origen de datos secundario, como datos proporcionados por un componente de nivel intermedio, quizás modificado por un usuario.If you select the Upsert option, it is assumed that the data is coming from one of a secondary data source, such as data provided by a middle-tier component, perhaps altered by a user. En este caso, la suposición es que la intención es agregar los datos de uno o varios orígenes de datos en el DataTabley, a continuación, tal vez propagar los datos en el origen de datos principal.In this case, the assumption is that the intent is to aggregate data from one or more data sources in the DataTable, and then perhaps propagate the data back to the primary data source. El LoadOption parámetro se usa para determinar la versión específica de la fila que se va a usar para la comparación de la clave principal.The LoadOption parameter is used for determining the specific version of the row that is to be used for primary key comparison. En la tabla siguiente proporciona los detalles.The table below provides the details.

Opción de cargaLoad option Versión de DataRow usada para la comparación de la clave principalDataRow version used for primary key comparison
OverwriteChanges Versión original, si existe, la versión actual de lo contrarioOriginal version, if it exists, otherwise Current version
PreserveChanges Versión original, si existe, la versión actual de lo contrarioOriginal version, if it exists, otherwise Current version
Upsert Versión actual, si existe, la versión Original en caso contrarioCurrent version, if it exists, otherwise Original version
Consulte también:

Load(IDataReader, LoadOption, FillErrorEventHandler) Load(IDataReader, LoadOption, FillErrorEventHandler) Load(IDataReader, LoadOption, FillErrorEventHandler)

Rellena un objeto DataTable con valores de un origen de datos utilizando la interfaz IDataReader proporcionada y un delegado de control de errores.Fills a DataTable with values from a data source using the supplied IDataReader using an error-handling delegate.

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

Parámetros

reader
IDataReader IDataReader IDataReader IDataReader

Interfaz IDataReader que proporciona un conjunto de resultados.A IDataReader that provides a result set.

loadOption
LoadOption LoadOption LoadOption LoadOption

Valor de la enumeración LoadOption que indica cómo se combinan las filas que ya existen en el objeto DataTable con las filas de entrada con las que comparten la misma clave principal.A value from the LoadOption enumeration that indicates how rows already in the DataTable are combined with incoming rows that share the same primary key.

errorHandler
FillErrorEventHandler FillErrorEventHandler FillErrorEventHandler FillErrorEventHandler

Delegado FillErrorEventHandler al que se va a llamar cuando se produzca un error mientras se cargan los datos.A FillErrorEventHandler delegate to call when an error occurs while loading data.

Ejemplos

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

Comentarios

El Load método consume el primer conjunto de resultados de la carga IDataReadery tras finalizar correctamente, Establece la posición del lector hasta el siguiente conjunto de resultados, si hay alguno.The Load method consumes the first result set from the loaded IDataReader, and after successful completion, sets the reader's position to the next result set, if any. Al convertir los datos, el Load método usa las mismas reglas de conversión que el DbDataAdapter.Fill método.When converting data, the Load method uses the same conversion rules as the DbDataAdapter.Fill method.

El Load método debe tener en cuenta tres aspectos concretos al cargar los datos desde un IDataReader instancia: operaciones de esquema, datos y eventos.The Load method must take into account three specific issues when loading the data from an IDataReader instance: schema, data, and event operations. Cuando se trabaja con el esquema, el Load método puede encontrar las condiciones como se describe en la tabla siguiente.When working with the schema, the Load method may encounter conditions as described in the following table. Las operaciones de esquema tienen lugar para todos los conjuntos de resultados importados, incluso aquellos que no contienen datos.The schema operations take place for all imported result sets, even those containing no data.

CondiciónCondition ComportamientoBehavior
El DataTable no tiene un esquema.The DataTable has no schema. El Load método deduce el esquema según el conjunto de resultados de la información importada IDataReader.The Load method infers the schema based on the result set from the imported IDataReader.
El DataTable tiene un esquema, pero no es compatible con el esquema cargado.The DataTable has a schema, but it is incompatible with the loaded schema. El Load método produce una excepción correspondiente al error concreto que se produce al intentar cargar datos en el esquema incompatible.The Load method throws an exception corresponding to the particular error that occurs when attempting to load data into the incompatible schema.
Los esquemas son compatibles, pero el esquema del conjunto de resultados cargado contiene columnas que no existen en el DataTable.The schemas are compatible, but the loaded result set schema contains columns that don't exist in the DataTable. El Load método agrega las columnas adicionales para DataTabledel esquema.The Load method adds the extra column(s) to DataTable's schema. El método produce una excepción si correspondientes columnas de la DataTable y el conjunto de resultados cargado no tienen valores compatibles.The method throws an exception if corresponding columns in the DataTable and the loaded result set are not value compatible. El método también recupera información de restricciones de conjunto de resultados de todas las columnas agregadas.The method also retrieves constraint information from the result set for all added columns. Excepto en el caso de una restricción Primary Key, se usa la información de esta restricción solo si actual DataTable no contiene ninguna columna al principio de la operación de carga.Except for the case of Primary Key constraint, this constraint information is used only if the current DataTable does not contain any columns at the start of the load operation.
Los esquemas son compatibles, pero el esquema del conjunto de resultados cargado contiene menos columnas que el DataTable.The schemas are compatible, but the loaded result set schema contains fewer columns than does the DataTable. Si falta una columna con un valor predeterminado definido o tipo de datos de la columna admite valores NULL, el Load método permite que las filas que se va a agregarse, sustituyendo el valor predeterminado o null para la columna que faltan.If a missing column has a default value defined or the column's data type is nullable, the Load method allows the rows to be added, substituting the default or null value for the missing column. Si no puede utilizarse valor predeterminado o null, el Load método produce una excepción.If no default value or null can be used, then the Load method throws an exception. Si no se ha proporcionado ningún valor predeterminado concreto, el Load método utiliza el valor null como valor predeterminado implícito.If no specific default value has been supplied, the Load method uses the null value as the implied default value.

Antes de considerar el comportamiento de la Load método en cuanto a operaciones de datos, considere la posibilidad de que cada fila dentro de un DataTable mantiene el valor actual y el valor original de cada columna.Before considering the behavior of the Load method in terms of data operations, consider that each row within a DataTable maintains both the current value and the original value for each column. Estos valores pueden ser equivalentes, o puede ser diferentes si los datos de la fila ha cambiado desde llene la DataTable.These values may be equivalent, or may be different if the data in the row has been changed since filling the DataTable. Consulte Estados de fila y las versiones de fila para obtener más información.See Row States and Row Versions for more information.

En esta llamada de método especificada LoadOption parámetro influye en el procesamiento de los datos entrantes.In this method call, the specified LoadOption parameter influences the processing of the incoming data. ¿Cómo debe controlar el método de carga al cargar las filas que tienen la misma clave principal que las filas existentes?How should the Load method handle loading rows that have the same primary key as existing rows? ¿Debe modificar los valores actuales, los valores originales o ambos?Should it modify current values, original values, or both? Estos problemas entre otros, se controlan mediante el loadOption parámetro.These issues, and more, are controlled by the loadOption parameter.

Si la fila existente y la fila entrante contienen valores de clave principal correspondientes, la fila se procesa mediante su valor de estado de fila actual, en caso contrario, se trata como una nueva fila.If the existing row and the incoming row contain corresponding primary key values, the row is processed using its current row state value, otherwise it's treated as a new row.

En cuanto a operaciones de evento, el RowChanging evento tiene lugar antes de que cambie cada fila y el RowChanged evento se produce después de cada fila ha cambiado.In terms of event operations, the RowChanging event occurs before each row is changed, and the RowChanged event occurs after each row has been changed. En cada caso, el Action propiedad de la DataRowChangeEventArgs instancia que se pasa al controlador de eventos contiene información acerca de la acción concreta asociada al evento.In each case, the Action property of the DataRowChangeEventArgs instance passed to the event handler contains information about the particular action associated with the event. Este valor de acción varía según el estado de la fila antes de la operación de carga.This action value varies, depending on the state of the row before the load operation. En cada caso, se produzcan ambos eventos y la acción es la misma para cada uno.In each case, both events occur, and the action is the same for each. La acción se puede aplicar a la versión actual o original de cada fila, o ambas, según el estado de la fila actual.The action may be applied to either the current or original version of each row, or both, depending on the current row state.

En la tabla siguiente muestra el comportamiento del método Load cuando se llama con cada uno de los LoadOption valores y también se muestra cómo interactúan los valores con el estado de fila para la fila que se está cargando.The following table displays behavior for the Load method when called with each of the LoadOption values, and also shows how the values interact with the row state for the row being loaded. La fila final (con la etiqueta "(no está presente)") describe el comportamiento de las filas entrantes que no coincide con ninguna fila existente.The final row (labeled "(Not present)") describes the behavior for incoming rows that don't match any existing row. Cada celda de esta tabla describe el valor actual y original de un campo dentro de una fila, junto con el DataRowState para el valor después de la Load método ha finalizado.Each cell in this table describes the current and original value for a field within a row, along with the DataRowState for the value after the Load method has completed.

DataRowState existenteExisting DataRowState UpsertUpsert OverwriteChangesOverwriteChanges PreserveChanges (comportamiento predeterminado)PreserveChanges (Default behavior)
AgregadoAdded Actual = <entrantes >Current = <Incoming>

Original = -<no disponible >Original = -<Not available>

Estado = <agregado >State = <Added>

RowAction = cambioRowAction = Change
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <existente >Current = <Existing>

Original = <entrantes >Original = <Incoming>

Estado = <modificado >State = <Modified>

RowAction = ChangeOriginalRowAction = ChangeOriginal
ModifiedModified Actual = <entrantes >Current = <Incoming>

Original = <existente >Original = <Existing>

Estado = <modificado >State = <Modified>

RowAction = cambioRowAction = Change
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <existente >Current = <Existing>

Original = <entrantes >Original = <Incoming>

Estado = <modificado >State = <Modified>

RowAction = ChangeOriginalRowAction =ChangeOriginal
eliminadoeleted (La carga no no afectan a eliminar las filas)(Load does not affect deleted rows)

Actual =---Current = ---

Original = <existente >Original = <Existing>

Estado = <eliminó >State = <Deleted>

(Se agrega una fila nueva con las siguientes características)(New row is added with the following characteristics)

Actual = <entrantes >Current = <Incoming>

Original = <no disponible >Original = <Not available>

Estado = <agregado >State = <Added>

RowAction = agregarRowAction = Add
Deshacer la eliminación yUndo delete and

Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <no disponible >Current = <Not available>

Original = <entrantes >Original = <Incoming>

Estado = <eliminó >State = <Deleted>

RowAction = ChangeOriginalRowAction = ChangeOriginal
Sin cambiosUnchanged Actual = <entrantes >Current = <Incoming>

Original = <existente >Original = <Existing>

Si el nuevo valor es igual que el valor existente, a continuaciónIf new value is the same as the existing value then

Estado = <sin cambios >State = <Unchanged>

RowAction = NothingRowAction = Nothing

ElseElse

Estado = <modificado >State = <Modified>

RowAction = cambioRowAction = Change
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
No está presente)Not present) Actual = <entrantes >Current = <Incoming>

Original = <no disponible >Original = <Not available>

Estado = <agregado >State = <Added>

RowAction = agregarRowAction = Add
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal
Actual = <entrantes >Current = <Incoming>

Original = <entrantes >Original = <Incoming>

Estado = <sin cambios >State = <Unchanged>

RowAction = ChangeCurrentAndOriginalRowAction = ChangeCurrentAndOriginal

Los valores en un DataColumn puede restringirse mediante el uso de propiedades, como ReadOnly y AutoIncrement.Values in a DataColumn can be constrained through use of properties such as ReadOnly and AutoIncrement. El Load método controla estas columnas de una manera coherente con el comportamiento definido por las propiedades de la columna.The Load method handles such columns in a manner that is consistent with the behavior defined by the column's properties. La restricción de sólo lectura en un DataColumn sólo es aplicable para los cambios producidos en la memoria.The read only constraint on a DataColumn is applicable only for changes that occur in memory. El Load método sobrescribe los valores de columna de sólo lectura, si es necesario.The Load method's overwrites the read-only column values, if needed.

Si especifica las opciones OverwriteChanges o PreserveChanges al llamar a la Load se realiza método y, a continuación, la suposición de que los datos de entrada procede de la DataTabledel origen de datos principal y la tabla de datos realiza un seguimiento de cambios y se pueden propagar los cambios en el origen de datos.If you specify the OverwriteChanges or PreserveChanges options when calling the Load method, then the assumption is made that the incoming data is coming from the DataTable's primary data source, and the DataTable tracks changes and can propagate the changes back to the data source. Si selecciona la opción Upsert, se supone que los datos proceden de uno de un origen de datos secundario, como datos proporcionados por un componente de nivel intermedio, quizás modificado por un usuario.If you select the Upsert option, it is assumed that the data is coming from one of a secondary data source, such as data provided by a middle-tier component, perhaps altered by a user. En este caso, la suposición es que la intención es agregar los datos de uno o varios orígenes de datos en el DataTabley, a continuación, tal vez propagar los datos en el origen de datos principal.In this case, the assumption is that the intent is to aggregate data from one or more data sources in the DataTable, and then perhaps propagate the data back to the primary data source. El LoadOption parámetro se usa para determinar la versión específica de la fila que se va a usar para la comparación de la clave principal.The LoadOption parameter is used for determining the specific version of the row that is to be used for primary key comparison. En la tabla siguiente proporciona los detalles.The table below provides the details.

Opción de cargaLoad option Versión de DataRow usada para la comparación de la clave principalDataRow version used for primary key comparison
OverwriteChanges Versión original, si existe, la versión actual de lo contrarioOriginal version, if it exists, otherwise Current version
PreserveChanges Versión original, si existe, la versión actual de lo contrarioOriginal version, if it exists, otherwise Current version
Upsert Versión actual, si existe, la versión Original en caso contrarioCurrent version, if it exists, otherwise Original version

El errorHandler parámetro es un FillErrorEventHandler delegado que hace referencia a un procedimiento que se llama cuando se produce un error al cargar los datos.The errorHandler parameter is a FillErrorEventHandler delegate that refers to a procedure that is called when an error occurs while loading data. El FillErrorEventArgs parámetro pasado al procedimiento proporciona propiedades que permiten recuperar información sobre el error que se ha producido, la fila actual de datos, y el DataTable se llena.The FillErrorEventArgs parameter passed to the procedure provides properties that allow you to retrieve information about the error that occurred, the current row of data, and the DataTable being filled. Mediante este mecanismo de delegado, en lugar de un bloque try/catch más sencillo, le permite determinar el error, controlar la situación y continuar procesando si lo desea.Using this delegate mechanism, rather than a simpler try/catch block, allows you to determine the error, handle the situation, and continue processing if you like. El FillErrorEventArgs parámetro proporciona un Continue propiedad: establezca esta propiedad en true para indicar que ha controlado el error y desea seguir procesando.The FillErrorEventArgs parameter supplies a Continue property: set this property to true to indicate that you have handled the error and wish to continue processing. Establezca la propiedad en false para indicar que desea detener el procesamiento.Set the property to false to indicate that you wish to halt processing. Tenga en cuenta que establecer la propiedad en false hace que el código que desencadena el problema para producir una excepción.Be aware that setting the property to false causes the code that triggered the problem to throw an exception.

Consulte también:

Se aplica a