DataTable.Load Metodo

Definizione

Riempie una classe DataTable con valori di un'origine dati utilizzando l'interfaccia IDataReader fornita. Se DataTable contiene già righe, i dati in arrivo dall'origine dati vengono uniti alle righe esistenti.

Overload

Load(IDataReader)

Riempie una classe DataTable con valori di un'origine dati utilizzando l'interfaccia IDataReader fornita. Se DataTable contiene già righe, i dati in arrivo dall'origine dati vengono uniti alle righe esistenti.

Load(IDataReader, LoadOption)

Riempie una classe DataTable con valori di un'origine dati utilizzando l'interfaccia IDataReader fornita. Se DataTable contiene già righe, i dati in arrivo dall'origine dati vengono uniti alle righe esistenti, in base al valore del parametro loadOption.

Load(IDataReader, LoadOption, FillErrorEventHandler)

Riempie una classe DataTable con valori di un'origine dati utilizzando l'interfaccia IDataReader fornita, tramite un delegato di gestione degli errori.

Esempio

Nell'esempio seguente vengono illustrati diversi problemi relativi alla chiamata al Load metodo . In primo luogo, l'esempio è incentrato sui problemi dello schema, tra cui l'inferenza di uno schema dal caricamento IDataReadere la gestione di schemi incompatibili con colonne mancanti o aggiuntive. L'esempio si concentra quindi sui problemi relativi ai dati, inclusa la gestione delle varie opzioni di caricamento.

Nota

In questo esempio viene illustrato come usare una delle versioni di overload di Load. Per altri esempi che potrebbero essere disponibili, vedere i singoli argomenti di overload.

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

Commenti

Il Load metodo può essere usato in diversi scenari comuni, tutti incentrati sull'acquisizione di dati da un'origine dati specificata e l'aggiunta al contenitore dati corrente (in questo caso, un DataTable). Questi scenari descrivono l'utilizzo standard per un DataTableoggetto , che descrive il relativo comportamento di aggiornamento e unione.

Un DataTable oggetto sincronizza o aggiorna con un'unica origine dati primaria. Le DataTable tracce vengono modificate, consentendo la sincronizzazione con l'origine dati primaria. Inoltre, un può DataTable accettare dati incrementali da una o più origini dati secondarie. Non DataTable è responsabile del rilevamento delle modifiche per consentire la sincronizzazione con l'origine dati secondaria.

Dato questi due origini dati ipotetiche, è probabile che un utente richieda uno dei comportamenti seguenti:

  • Inizializzare DataTable da un'origine dati primaria. In questo scenario l'utente vuole inizializzare un oggetto vuoto DataTable con valori dall'origine dati primaria. In seguito l'utente intende propagare le modifiche all'origine dati primaria.

  • Mantenere le modifiche e sincronizzare nuovamente dall'origine dati primaria. In questo scenario, l'utente vuole eseguire il DataTable riempimento nello scenario precedente ed eseguire una sincronizzazione incrementale con l'origine dati primaria, mantenendo le modifiche apportate nell'oggetto DataTable.

  • Feed di dati incrementali da origini dati secondarie. In questo scenario, l'utente vuole unire le modifiche da una o più origini dati secondarie e propagare tali modifiche all'origine dati primaria.

Il Load metodo rende possibile tutti questi scenari. Tutti gli overload per questo metodo consentono di specificare un parametro di opzione di caricamento, che indica come le righe già presenti in una DataTable combinazione con le righe caricate. L'overload che non consente di specificare il comportamento usa l'opzione di caricamento predefinita. Nella tabella seguente vengono descritte le tre opzioni di carico fornite dall'enumerazione LoadOption . In ogni caso, la descrizione indica il comportamento quando la chiave primaria di una riga nei dati in ingresso corrisponde alla chiave primaria di una riga esistente.

Opzione di caricamento Descrizione
PreserveChanges (impostazione predefinita) Aggiornamenti la versione originale della riga con il valore della riga in ingresso.
OverwriteChanges Aggiornamenti le versioni correnti e originali della riga con il valore della riga in ingresso.
Upsert Aggiornamenti la versione corrente della riga con il valore della riga in ingresso.

In generale, le PreserveChanges opzioni e OverwriteChanges sono destinate agli scenari in cui l'utente deve sincronizzare e DataSet le relative modifiche con l'origine dati primaria. L'opzione facilita l'aggregazione Upsert delle modifiche da una o più origini dati secondarie.

Load(IDataReader)

Riempie una classe DataTable con valori di un'origine dati utilizzando l'interfaccia IDataReader fornita. Se DataTable contiene già righe, i dati in arrivo dall'origine dati vengono uniti alle righe esistenti.

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)

Parametri

reader
IDataReader

Interfaccia IDataReader che fornisce un gruppo di risultati.

Esempio

Nell'esempio seguente vengono illustrati diversi problemi relativi alla chiamata al Load metodo . In primo luogo, l'esempio è incentrato sui problemi dello schema, tra cui l'inferenza di uno schema dal caricamento IDataReadere la gestione di schemi incompatibili con colonne mancanti o aggiuntive. L'esempio chiama quindi il Load metodo, visualizzando i dati sia prima che dopo l'operazione di caricamento.

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

Commenti

Il Load metodo utilizza il primo set di risultati dal caricamento IDataReadere dopo il completamento, imposta la posizione del lettore sul set di risultati successivo, se presente. Durante la conversione dei dati, il Load metodo usa le stesse regole di conversione del DbDataAdapter.Fill metodo.

Il Load metodo deve tenere conto di tre problemi specifici durante il caricamento dei dati da un'istanza IDataReader : schema, dati e operazioni di evento. Quando si usa lo schema, il Load metodo può riscontrare condizioni come descritto nella tabella seguente. Le operazioni dello schema vengono eseguite per tutti i set di risultati importati, anche quelli che non contengono dati.

Condizione Comportamento
L'oggetto DataTable non ha uno schema. Il Load metodo inferisce lo schema in base al set di risultati dall'oggetto importato IDataReader.
Ha DataTable uno schema, ma è incompatibile con lo schema caricato. Il Load metodo genera un'eccezione corrispondente all'errore specifico che si verifica quando si tenta di caricare i dati nello schema incompatibile.
Gli schemi sono compatibili, ma lo schema del set di risultati caricato contiene colonne che non esistono in DataTable. Il Load metodo aggiunge le colonne aggiuntive allo DataTableschema. Il metodo genera un'eccezione DataTable se le colonne corrispondenti nel set di risultati caricato non sono compatibili con il valore. Il metodo recupera anche le informazioni sui vincoli dal set di risultati per tutte le colonne aggiunte. Ad eccezione del caso del vincolo Chiave primaria, queste informazioni sui vincoli vengono usate solo se l'oggetto corrente DataTable non contiene colonne all'inizio dell'operazione di caricamento.
Gli schemi sono compatibili, ma lo schema del set di risultati caricato contiene meno colonne rispetto a .DataTable Se una colonna mancante ha un valore predefinito definito o il tipo di dati della colonna è nullable, il Load metodo consente di aggiungere le righe, sostituendo il valore predefinito o null il valore per la colonna mancante. Se non è possibile usare alcun valore predefinito o null può essere usato, il Load metodo genera un'eccezione. Se non è stato specificato alcun valore predefinito specifico, il metodo usa il Loadnull valore come valore predefinito implicito.

Prima di considerare il comportamento del Load metodo in termini di operazioni sui dati, considerare che ogni riga all'interno di una DataTable mantiene sia il valore corrente che il valore originale per ogni colonna. Questi valori possono essere equivalenti o possono essere diversi se i dati nella riga sono stati modificati dopo aver compilato .DataTable Per altre informazioni, vedere Stati di riga e versioni di riga.

Questa versione del Load metodo tenta di mantenere i valori correnti in ogni riga, lasciando invariato il valore originale. Se si vuole controllare il comportamento dei dati in ingresso, vedere DataTable.Load.) Se la riga esistente e la riga in ingresso contengono valori chiave primaria corrispondenti, la riga viene elaborata usando il valore dello stato della riga corrente, in caso contrario viene considerata come nuova riga.

In termini di operazioni di evento, l'evento RowChanging si verifica prima della modifica di ogni riga e l'evento RowChanged si verifica dopo la modifica di ogni riga. In ogni caso, la Action proprietà dell'istanza DataRowChangeEventArgs passata al gestore eventi contiene informazioni sull'azione specifica associata all'evento. Questo valore di azione dipende dallo stato della riga prima dell'operazione di caricamento. In ogni caso, entrambi gli eventi si verificano e l'azione è uguale per ogni evento. L'azione può essere applicata alla versione corrente o originale di ogni riga o a seconda dello stato della riga corrente.

Nella tabella seguente viene visualizzato il comportamento per il Load metodo . La riga finale (etichettata "(Non presente)") descrive il comportamento per le righe in ingresso che non corrispondono a alcuna riga esistente. Ogni cella di questa tabella descrive il valore corrente e originale per un campo all'interno di una riga, insieme al DataRowState valore dopo il completamento del Load metodo. In questo caso, il metodo non consente di indicare l'opzione di caricamento e usa il valore predefinito , PreserveChanges.

DataRowState esistente Valori dopo Load il metodo e l'azione dell'evento
Aggiunta Current = <esistente>

Originale = <In ingresso>

Stato = <Modificato>

RowAction = ChangeOriginal
Ultima modifica Current = <esistente>

Originale = <In ingresso>

Stato = <Modificato>

RowAction = ChangeOriginal
Eliminata Current = <Non disponibile>

Originale = <In ingresso>

Stato = <Eliminato>

RowAction = ChangeOriginal
Non modificato Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
(Non presente) Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal

I valori in un DataColumn oggetto possono essere vincolati tramite l'uso di proprietà, ReadOnly ad esempio e AutoIncrement. Il Load metodo gestisce tali colonne in modo coerente con il comportamento definito dalle proprietà della colonna. Il vincolo di sola lettura su un DataColumn è applicabile solo per le modifiche che si verificano in memoria. Il Load metodo sovrascrive i valori di colonna di sola lettura, se necessario.

Per determinare quale versione del campo chiave primaria usare per confrontare la riga corrente con una riga in ingresso, il Load metodo usa la versione originale del valore della chiave primaria all'interno di una riga, se presente. In caso contrario, il Load metodo usa la versione corrente del campo chiave primaria.

Vedi anche

Si applica a

Load(IDataReader, LoadOption)

Riempie una classe DataTable con valori di un'origine dati utilizzando l'interfaccia IDataReader fornita. Se DataTable contiene già righe, i dati in arrivo dall'origine dati vengono uniti alle righe esistenti, in base al valore del parametro loadOption.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption);
member this.Load : System.Data.IDataReader * System.Data.LoadOption -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption)

Parametri

reader
IDataReader

Interfaccia IDataReader che fornisce uno o più gruppi di risultati.

loadOption
LoadOption

Valore dall'enumerazione della classe LoadOption, che indica come vengono combinate le righe già presenti nella classe DataTable con le righe in entrata che condividono la stessa chiave primaria.

Esempio

Nell'esempio seguente vengono illustrati diversi problemi relativi alla chiamata al Load metodo . In primo luogo, l'esempio è incentrato sui problemi dello schema, tra cui l'inferenza di uno schema dal caricamento IDataReadere la gestione di schemi incompatibili con colonne mancanti o aggiuntive. L'esempio si concentra quindi sui problemi relativi ai dati, inclusa la gestione delle varie opzioni di caricamento.

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

Commenti

Il Load metodo utilizza il primo set di risultati dall'oggetto caricato IDataReadere, dopo il completamento, imposta la posizione del lettore sul set di risultati successivo, se presente. Quando si convertono dati, il Load metodo utilizza le stesse regole di conversione del Fill metodo .

Il Load metodo deve tenere conto di tre problemi specifici durante il caricamento dei dati da un'istanza IDataReader : schema, dati ed operazioni di evento. Quando si usa lo schema, il Load metodo può riscontrare condizioni come descritto nella tabella seguente. Le operazioni dello schema vengono eseguite per tutti i set di risultati importati, anche per quelli che non contengono dati.

Condizione Comportamento
L'oggetto DataTable non ha uno schema. Il Load metodo deduce lo schema in base al set di risultati dall'oggetto importato IDataReader.
ha DataTable uno schema, ma non è compatibile con lo schema caricato. Il Load metodo genera un'eccezione corrispondente all'errore specifico che si verifica quando si tenta di caricare dati nello schema incompatibile.
Gli schemi sono compatibili, ma lo schema del set di risultati caricato contiene colonne che non esistono in DataTable. Il Load metodo aggiunge le colonne aggiuntive allo DataTableschema di . Il metodo genera un'eccezione se le colonne corrispondenti nel DataTable e il set di risultati caricato non sono compatibili con il valore. Il metodo recupera anche le informazioni sui vincoli dal set di risultati per tutte le colonne aggiunte. Ad eccezione del caso del vincolo Di chiave primaria, queste informazioni sul vincolo vengono utilizzate solo se l'oggetto corrente DataTable non contiene colonne all'inizio dell'operazione di caricamento.
Gli schemi sono compatibili, ma lo schema del set di risultati caricato contiene meno colonne rispetto a DataTable. Se una colonna mancante ha un valore predefinito definito o il tipo di dati della colonna è nullable, il Load metodo consente di aggiungere le righe, sostituendo il valore predefinito o Null per la colonna mancante. Se non è possibile usare alcun valore predefinito o Null, il Load metodo genera un'eccezione. Se non è stato specificato alcun valore predefinito specifico, il Load metodo usa il valore Null come valore predefinito implicito.

Prima di considerare il comportamento del Load metodo in termini di operazioni sui dati, tenere presente che ogni riga all'interno di un DataTable mantiene sia il valore corrente che il valore originale per ogni colonna. Questi valori possono essere equivalenti o possono essere diversi se i dati nella riga sono stati modificati dopo la compilazione di DataTable. Per altre informazioni, vedere Stati di riga e versioni di riga .

In questa chiamata al metodo, il parametro specificato LoadOption influenza l'elaborazione dei dati in ingresso. In che modo il metodo Load deve gestire il caricamento di righe con la stessa chiave primaria delle righe esistenti? Deve modificare i valori correnti, i valori originali o entrambi? Questi problemi, e altro ancora, sono controllati dal loadOption parametro .

Se la riga esistente e la riga in ingresso contengono i valori di chiave primaria corrispondenti, la riga viene elaborata utilizzando il relativo valore di stato di riga corrente, altrimenti viene considerata come una nuova riga.

In termini di operazioni sugli eventi, l'evento RowChanging si verifica prima della modifica di ogni riga e l'evento RowChanged si verifica dopo la modifica di ogni riga. In ogni caso, la Action proprietà dell'istanza DataRowChangeEventArgs passata al gestore eventi contiene informazioni sull'azione specifica associata all'evento. Questo valore di azione varia a seconda dello stato della riga prima dell'operazione di caricamento. In ogni caso, si verificano entrambi gli eventi e l'azione è la stessa per ogni evento. L'azione può essere applicata alla versione corrente o originale di ogni riga o a entrambe, a seconda dello stato corrente della riga.

Nella tabella seguente viene visualizzato il comportamento del metodo Load quando viene chiamato con ognuno dei LoadOption valori e viene inoltre illustrato come i valori interagiscono con lo stato della riga da caricare. La riga finale (con etichetta "(Non presente)") descrive il comportamento per le righe in ingresso che non corrispondono ad alcuna riga esistente. Ogni cella di questa tabella descrive il valore corrente e originale per un campo all'interno di una riga, insieme a per DataRowState il valore dopo il completamento del Load metodo.

DataRowState esistente Upsert OverwriteChanges PreserveChanges (comportamento predefinito)
Aggiunta Current = <Incoming>

Originale = -<Non disponibile>

State = <Added>

RowAction = Modifica
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal
Ultima modifica Current = <Incoming>

Original = <Existing>

State = <Modified>

RowAction = Modifica
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction =ChangeOriginal
Eliminata (Il caricamento non influisce sulle righe eliminate)

Current = ---

Original = <Existing>

State = <Deleted>

(Viene aggiunta una nuova riga con le caratteristiche seguenti)

Current = <Incoming>

Originale = <Non disponibile>

State = <Added>

RowAction = Aggiungi
Annullare l'eliminazione e

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Non disponibile>

Original = <Incoming>

State = <Deleted>

RowAction = ChangeOriginal
Non modificato Current = <Incoming>

Original = <Existing>

Se il nuovo valore è uguale al valore esistente,

State = <Unchanged>

RowAction = Nothing

Else

State = <Modified>

RowAction = Modifica
Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
Non presente) Current = <Incoming>

Originale = <Non disponibile>

Stato = <Aggiunto>

RowAction = Aggiungi
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal

I valori in un DataColumn oggetto possono essere vincolati tramite l'uso di proprietà, ReadOnly ad esempio e AutoIncrement. Il Load metodo gestisce tali colonne in modo coerente con il comportamento definito dalle proprietà della colonna. Il vincolo di sola lettura su un DataColumn è applicabile solo per le modifiche che si verificano in memoria. Il Load metodo sovrascrive i valori di colonna di sola lettura, se necessario.

Se si specificano le opzioni OverwriteChanges o PreserveChanges quando si chiama il Load metodo, viene effettuato il presupposto che i dati in ingresso provengono dall'origine DataTabledati primaria e dataTable tiene traccia delle modifiche e possono propagare le modifiche all'origine dati. Se si seleziona l'opzione Upsert, si presuppone che i dati vengano provenienti da un'origine dati secondaria, ad esempio i dati forniti da un componente di livello intermedio, forse modificati da un utente. In questo caso, il presupposto è che la finalità consiste nell'aggregare i dati da una o più origini dati in DataTablee quindi propagare i dati all'origine dati primaria. Il LoadOption parametro viene usato per determinare la versione specifica della riga da usare per il confronto tra chiavi primarie. La tabella seguente fornisce i dettagli.

Opzione di caricamento Versione di DataRow usata per il confronto tra chiavi primarie
OverwriteChanges Versione originale, se esistente, in caso contrario versione corrente
PreserveChanges Versione originale, se esistente, in caso contrario versione corrente
Upsert Versione corrente, se esistente, in caso contrario versione originale

Vedi anche

Si applica a

Load(IDataReader, LoadOption, FillErrorEventHandler)

Riempie una classe DataTable con valori di un'origine dati utilizzando l'interfaccia IDataReader fornita, tramite un delegato di gestione degli errori.

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);
public virtual void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler);
abstract member Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler -> unit
Public Overridable Sub Load (reader As IDataReader, loadOption As LoadOption, errorHandler As FillErrorEventHandler)

Parametri

reader
IDataReader

Interfaccia IDataReader che fornisce un gruppo di risultati.

loadOption
LoadOption

Valore dall'enumerazione della classe LoadOption, che indica come vengono combinate le righe già presenti nella classe DataTable con le righe in entrata che condividono la stessa chiave primaria.

errorHandler
FillErrorEventHandler

Delegato FillErrorEventHandler da chiamare quando si verifica un errore durante il caricamento dei dati.

Esempio

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

Commenti

Il Load metodo utilizza il primo set di risultati dal caricamento IDataReadere dopo il completamento, imposta la posizione del lettore sul set di risultati successivo, se presente. Durante la conversione dei dati, il Load metodo usa le stesse regole di conversione del DbDataAdapter.Fill metodo.

Il Load metodo deve tenere conto di tre problemi specifici durante il caricamento dei dati da un'istanza IDataReader : schema, dati e operazioni di evento. Quando si usa lo schema, il Load metodo può riscontrare condizioni come descritto nella tabella seguente. Le operazioni dello schema vengono eseguite per tutti i set di risultati importati, anche quelli che non contengono dati.

Condizione Comportamento
L'oggetto DataTable non ha uno schema. Il Load metodo inferisce lo schema in base al set di risultati dall'oggetto importato IDataReader.
Ha DataTable uno schema, ma è incompatibile con lo schema caricato. Il Load metodo genera un'eccezione corrispondente all'errore specifico che si verifica quando si tenta di caricare i dati nello schema incompatibile.
Gli schemi sono compatibili, ma lo schema del set di risultati caricato contiene colonne che non esistono in DataTable. Il Load metodo aggiunge le colonne aggiuntive allo DataTableschema. Il metodo genera un'eccezione DataTable se le colonne corrispondenti nel set di risultati caricato non sono compatibili con il valore. Il metodo recupera anche le informazioni sui vincoli dal set di risultati per tutte le colonne aggiunte. Ad eccezione del caso del vincolo Chiave primaria, queste informazioni sui vincoli vengono usate solo se l'oggetto corrente DataTable non contiene colonne all'inizio dell'operazione di caricamento.
Gli schemi sono compatibili, ma lo schema del set di risultati caricato contiene meno colonne rispetto a .DataTable Se una colonna mancante ha un valore predefinito definito o il tipo di dati della colonna è nullable, il Load metodo consente l'aggiunta delle righe, sostituendo il valore predefinito o Null per la colonna mancante. Se non è possibile usare alcun valore predefinito o Null, il Load metodo genera un'eccezione. Se non è stato specificato alcun valore predefinito specifico, il metodo usa il Load valore Null come valore predefinito implicito.

Prima di considerare il comportamento del Load metodo in termini di operazioni sui dati, considerare che ogni riga all'interno di una DataTable mantiene sia il valore corrente che il valore originale per ogni colonna. Questi valori possono essere equivalenti o possono essere diversi se i dati nella riga sono stati modificati dopo aver compilato .DataTable Per altre informazioni, vedere Stati di riga e versioni di riga .

In questa chiamata al metodo il parametro specificato LoadOption influisce sull'elaborazione dei dati in ingresso. In che modo il metodo Load gestisce il caricamento di righe con la stessa chiave primaria delle righe esistenti? È consigliabile modificare i valori correnti, i valori originali o entrambi? Questi problemi, e altro ancora, sono controllati dal loadOption parametro.

Se la riga esistente e la riga in ingresso contengono valori chiave primaria corrispondenti, la riga viene elaborata usando il valore dello stato della riga corrente, in caso contrario viene considerata come nuova riga.

In termini di operazioni di evento, l'evento RowChanging si verifica prima della modifica di ogni riga e l'evento RowChanged si verifica dopo la modifica di ogni riga. In ogni caso, la Action proprietà dell'istanza DataRowChangeEventArgs passata al gestore eventi contiene informazioni sull'azione specifica associata all'evento. Questo valore di azione varia a seconda dello stato della riga prima dell'operazione di caricamento. In ogni caso, entrambi gli eventi si verificano e l'azione è uguale per ogni evento. L'azione può essere applicata alla versione corrente o originale di ogni riga o a seconda dello stato della riga corrente.

La tabella seguente visualizza il comportamento per il metodo Load quando viene chiamato con ognuno dei LoadOption valori e mostra anche come i valori interagiscono con lo stato della riga per la riga caricata. La riga finale (etichettata "(Non presente)") descrive il comportamento per le righe in ingresso che non corrispondono a alcuna riga esistente. Ogni cella di questa tabella descrive il valore corrente e originale per un campo all'interno di una riga, insieme al DataRowState valore dopo il completamento del Load metodo.

DataRowState esistente Upsert SovrascrivereChanges PreserveChanges (comportamento predefinito)
Aggiunta Current = <Incoming>

Originale = -<Non disponibile>

Stato = <Aggiunto>

RowAction = Modifica
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
Current = <esistente>

Originale = <In ingresso>

Stato = <Modificato>

RowAction = ChangeOriginal
Ultima modifica Current = <Incoming>

Originale = <esistente>

Stato = <Modificato>

RowAction = Modifica
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
Current = <esistente>

Originale = <In ingresso>

Stato = <Modificato>

RowAction =ChangeOriginal
eleted (Il caricamento non influisce sulle righe eliminate)

Current = ---

Originale = <esistente>

Stato = <Eliminato>

(Viene aggiunta una nuova riga con le caratteristiche seguenti)

Current = <Incoming>

Originale = <Non disponibile>

Stato = <Aggiunto>

RowAction = Aggiungi
Annullare l'eliminazione e

Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
Current = <Non disponibile>

Originale = <In ingresso>

Stato = <Eliminato>

RowAction = ChangeOriginal
Non modificato Current = <Incoming>

Originale = <esistente>

Se il nuovo valore è uguale al valore esistente,

Stato = <invariato>

RowAction = Nothing

Else

Stato = <Modificato>

RowAction = Modifica
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
Non presente) Current = <Incoming>

Originale = <Non disponibile>

Stato = <Aggiunto>

RowAction = Aggiungi
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal
Current = <Incoming>

Originale = <In ingresso>

Stato = <invariato>

RowAction = ChangeCurrentAndOriginal

I valori in un DataColumn oggetto possono essere vincolati tramite l'uso di proprietà, ReadOnly ad esempio e AutoIncrement. Il Load metodo gestisce tali colonne in modo coerente con il comportamento definito dalle proprietà della colonna. Il vincolo di sola lettura su un DataColumn è applicabile solo per le modifiche che si verificano in memoria. Il Load metodo sovrascrive i valori di colonna di sola lettura, se necessario.

Se si specificano le opzioni OverwriteChanges o PreserveChanges quando si chiama il Load metodo, viene effettuato il presupposto che i dati in ingresso provengono dall'origine DataTabledati primaria e dataTable tiene traccia delle modifiche e possono propagare le modifiche all'origine dati. Se si seleziona l'opzione Upsert, si presuppone che i dati vengano provenienti da un'origine dati secondaria, ad esempio i dati forniti da un componente di livello intermedio, forse modificati da un utente. In questo caso, il presupposto è che la finalità consiste nell'aggregare i dati da una o più origini dati in DataTablee quindi propagare i dati all'origine dati primaria. Il LoadOption parametro viene usato per determinare la versione specifica della riga da usare per il confronto tra chiavi primarie. La tabella seguente fornisce i dettagli.

Opzione di caricamento Versione di DataRow usata per il confronto tra chiavi primarie
OverwriteChanges Versione originale, se esistente, in caso contrario versione corrente
PreserveChanges Versione originale, se esistente, in caso contrario versione corrente
Upsert Versione corrente, se esistente, in caso contrario versione originale

Il errorHandler parametro è un delegato che fa riferimento a una FillErrorEventHandler routine chiamata quando si verifica un errore durante il caricamento dei dati. Il FillErrorEventArgs parametro passato alla routine fornisce proprietà che consentono di recuperare informazioni sull'errore che si è verificato, sulla riga corrente dei dati e sulla DataTable compilazione. L'uso di questo meccanismo delegato, anziché un blocco try/catch più semplice, consente di determinare l'errore, gestire la situazione e continuare l'elaborazione se si desidera. Il FillErrorEventArgs parametro fornisce una Continue proprietà: impostare questa proprietà su per true indicare che è stato gestito l'errore e si desidera continuare l'elaborazione. Impostare la proprietà su false per indicare che si vuole interrompere l'elaborazione. Tenere presente che l'impostazione della proprietà per false causare il codice che ha attivato il problema per generare un'eccezione.

Vedi anche

Si applica a