DataTable.Load Méthode

Définition

Remplit un DataTable avec des valeurs issues d'une source de données à l'aide du IDataReader fourni. Si DataTable contient déjà des lignes, les données entrantes à partir de la source de données sont fusionnées avec les lignes existantes.

Surcharges

Load(IDataReader)

Remplit un DataTable avec des valeurs issues d'une source de données à l'aide du IDataReader fourni. Si DataTable contient déjà des lignes, les données entrantes à partir de la source de données sont fusionnées avec les lignes existantes.

Load(IDataReader, LoadOption)

Remplit un DataTable avec des valeurs issues d'une source de données à l'aide du IDataReader fourni. Si DataTable contient déjà des lignes, les données entrantes à partir de la source de données sont fusionnées avec les lignes existantes en fonction de la valeur du paramètre loadOption.

Load(IDataReader, LoadOption, FillErrorEventHandler)

Remplit un DataTable avec des valeurs issues d'une source de données à l'aide du IDataReader fourni et d'un délégué de gestion d'erreur.

Exemples

L’exemple suivant illustre plusieurs des problèmes liés à l’appel de la Load méthode . Tout d’abord, l’exemple se concentre sur les problèmes de schéma, notamment la déduction d’un schéma à partir du chargé IDataReader, puis la gestion des schémas incompatibles et des schémas avec des colonnes manquantes ou supplémentaires. L’exemple se concentre ensuite sur les problèmes de données, y compris la gestion des différentes options de chargement.

Notes

Cet exemple montre comment utiliser l’une des versions surchargées de Load. Pour obtenir d’autres exemples qui peuvent être disponibles, consultez les rubriques sur les surcharges individuelles.

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

Remarques

La Load méthode peut être utilisée dans plusieurs scénarios courants, tous centrés sur l’obtention de données à partir d’une source de données spécifiée et leur ajout au conteneur de données actuel (dans ce cas, un DataTable). Ces scénarios décrivent l’utilisation standard d’un DataTable, en décrivant son comportement de mise à jour et de fusion.

Un DataTable synchronise ou met à jour avec une seule source de données primaire. Effectue le DataTable suivi des modifications, ce qui permet la synchronisation avec la source de données primaire. En outre, un DataTable peut accepter des données incrémentielles provenant d’une ou de plusieurs sources de données secondaires. Le DataTable n’est pas responsable du suivi des modifications afin d’autoriser la synchronisation avec la source de données secondaire.

Compte tenu de ces deux sources de données hypothétiques, un utilisateur est susceptible d’exiger l’un des comportements suivants :

  • Initialiser DataTable à partir d’une source de données primaire. Dans ce scénario, l’utilisateur souhaite initialiser un vide DataTable avec des valeurs de la source de données primaire. Par la suite, l’utilisateur a l’intention de propager les modifications à la source de données primaire.

  • Conservez les modifications et resynchronisez à partir de la source de données primaire. Dans ce scénario, l’utilisateur souhaite prendre le DataTable renseigné dans le scénario précédent et effectuer une synchronisation incrémentielle avec la source de données primaire, en conservant les modifications apportées dans le DataTable.

  • Flux de données incrémentiel à partir de sources de données secondaires. Dans ce scénario, l’utilisateur souhaite fusionner les modifications d’une ou plusieurs sources de données secondaires et les propager à la source de données primaire.

La Load méthode rend tous ces scénarios possibles. Toutes les surcharges de cette méthode, sauf une, vous permettent de spécifier un paramètre d’option de chargement, indiquant comment les lignes déjà dans une DataTable combinaison avec les lignes en cours de chargement. (La surcharge qui ne vous permet pas de spécifier le comportement utilise l’option de chargement par défaut.) Le tableau suivant décrit les trois options de chargement fournies par l’énumération LoadOption . Dans chaque cas, la description indique le comportement lorsque la clé primaire d’une ligne dans les données entrantes correspond à la clé primaire d’une ligne existante.

Option de chargement Description
PreserveChanges (valeur par défaut) Mises à jour la version d’origine de la ligne avec la valeur de la ligne entrante.
OverwriteChanges Mises à jour les versions actuelles et d’origine de la ligne avec la valeur de la ligne entrante.
Upsert Mises à jour la version actuelle de la ligne avec la valeur de la ligne entrante.

En général, les PreserveChanges options et OverwriteChanges sont destinées aux scénarios dans lesquels l’utilisateur doit synchroniser les DataSet modifications et avec la source de données primaire. L’option Upsert facilite l’agrégation des modifications à partir d’une ou plusieurs sources de données secondaires.

Load(IDataReader)

Source:
DataTable.cs
Source:
DataTable.cs
Source:
DataTable.cs

Remplit un DataTable avec des valeurs issues d'une source de données à l'aide du IDataReader fourni. Si DataTable contient déjà des lignes, les données entrantes à partir de la source de données sont fusionnées avec les lignes existantes.

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)

Paramètres

reader
IDataReader

IDataReader qui fournit un jeu de résultats.

Exemples

L’exemple suivant illustre plusieurs des problèmes liés à l’appel de la Load méthode . Tout d’abord, l’exemple se concentre sur les problèmes de schéma, notamment la déduction d’un schéma à partir du chargé IDataReader, puis la gestion des schémas incompatibles et des schémas avec des colonnes manquantes ou supplémentaires. L’exemple appelle ensuite la Load méthode, affichant les données avant et après l’opération de chargement.

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

Remarques

La Load méthode consomme le premier jeu de résultats à partir du chargé IDataReaderet, une fois l’exécution réussie, définit la position du lecteur sur le jeu de résultats suivant, le cas échéant. Lors de la conversion de données, la Load méthode utilise les mêmes règles de conversion que la DbDataAdapter.Fill méthode .

La Load méthode doit prendre en compte trois problèmes spécifiques lors du chargement des données à partir d’un IDataReader instance : schéma, données et opérations d’événement. Lors de l’utilisation du schéma, la Load méthode peut rencontrer des conditions comme décrit dans le tableau suivant. Les opérations de schéma ont lieu pour tous les jeux de résultats importés, même ceux qui ne contiennent aucune donnée.

Condition Comportement
le n’a pas de DataTable schéma. La Load méthode déduit le schéma en fonction du jeu de résultats de l’importé IDataReader.
a DataTable un schéma, mais il n’est pas compatible avec le schéma chargé. La Load méthode lève une exception correspondant à l’erreur particulière qui se produit lors de la tentative de chargement de données dans le schéma incompatible.
Les schémas sont compatibles, mais le schéma du jeu de résultats chargé contient des colonnes qui n’existent pas dans le DataTable. La Load méthode ajoute les colonnes supplémentaires au DataTableschéma de . La méthode lève une exception si les colonnes correspondantes dans et DataTable le jeu de résultats chargé ne sont pas compatibles avec la valeur. La méthode récupère également des informations de contrainte à partir du jeu de résultats pour toutes les colonnes ajoutées. Sauf dans le cas de la contrainte de clé primaire, ces informations de contrainte sont utilisées uniquement si le actuel DataTable ne contient pas de colonnes au début de l’opération de chargement.
Les schémas sont compatibles, mais le schéma du jeu de résultats chargé contient moins de colonnes que le DataTable. Si une colonne manquante a une valeur par défaut définie ou si le type de données de la colonne est nullable, la Load méthode permet d’ajouter les lignes, en remplaçant la valeur par défaut ou null la valeur de la colonne manquante. Si aucune valeur par défaut ou null ne peut être utilisée, la Load méthode lève une exception. Si aucune valeur par défaut spécifique n’a été fournie, la Load méthode utilise la null valeur comme valeur par défaut implicite.

Avant d’envisager le comportement de la Load méthode en termes d’opérations de données, tenez compte du fait que chaque ligne d’un DataTable conserve à la fois la valeur actuelle et la valeur d’origine pour chaque colonne. Ces valeurs peuvent être équivalentes ou différentes si les données de la ligne ont été modifiées depuis le remplissage de .DataTable Pour plus d’informations, consultez États des lignes et versions de ligne.

Cette version de la Load méthode tente de conserver les valeurs actuelles dans chaque ligne, en laissant la valeur d’origine intacte. (Si vous souhaitez contrôler plus finement le comportement des données entrantes, consultez DataTable.Load.) Si la ligne existante et la ligne entrante contiennent des valeurs de clé primaire correspondantes, la ligne est traitée à l’aide de sa valeur d’état de ligne actuelle, sinon elle est traitée comme une nouvelle ligne.

En termes d’opérations d’événement, l’événement RowChanging se produit avant que chaque ligne ne soit modifiée, et l’événement RowChanged se produit après chaque ligne a été modifiée. Dans chaque cas, la Action propriété de l’instance DataRowChangeEventArgs passée au gestionnaire d’événements contient des informations sur l’action particulière associée à l’événement. Cette valeur d’action dépend de l’état de la ligne avant l’opération de chargement. Dans chaque cas, les deux événements se produisent, et l’action est la même pour chacun d’eux. L’action peut être appliquée à la version actuelle ou à la version d’origine de chaque ligne, ou aux deux, selon l’état actuel de la ligne.

Le tableau suivant affiche le comportement de la Load méthode . La dernière ligne (intitulée « (Non présent) ») décrit le comportement des lignes entrantes qui ne correspondent à aucune ligne existante. Chaque cellule de ce tableau décrit la valeur actuelle et d’origine d’un champ dans une ligne, ainsi que le DataRowState pour la valeur une fois la Load méthode terminée. Dans ce cas, la méthode ne vous permet pas d’indiquer l’option de chargement et utilise la valeur par défaut, PreserveChanges.

DataRowState existant Valeurs après Load la méthode et l’action d’événement
Ajout Current = <Existant>

Original = <Entrant>

État = <Modifié>

RowAction = ChangeOriginal
Modifié le Current = <Existant>

Original = <Entrant>

État = <Modifié>

RowAction = ChangeOriginal
Deleted Current = <Non disponible>

Original = <Entrant>

État = <Supprimé>

RowAction = ChangeOriginal
Inchangé Current = <Entrant>

Original = <Entrant>

État = <inchangé>

RowAction = ChangeCurrentAndOriginal
(Non présent) Current = <Entrant>

Original = <Entrant>

État = <inchangé>

RowAction = ChangeCurrentAndOriginal

Les valeurs d’un DataColumn peuvent être limitées par l’utilisation de propriétés telles que ReadOnly et AutoIncrement. La Load méthode gère ces colonnes d’une manière cohérente avec le comportement défini par les propriétés de la colonne. La contrainte en lecture seule sur un DataColumn s’applique uniquement aux modifications qui se produisent dans la mémoire. Si Load nécessaire, la méthode remplace les valeurs de colonne en lecture seule.

Pour déterminer la version du champ de clé primaire à utiliser pour comparer la ligne actuelle avec une ligne entrante, la Load méthode utilise la version d’origine de la valeur de clé primaire dans une ligne, si elle existe. Sinon, la Load méthode utilise la version actuelle du champ de clé primaire.

Voir aussi

S’applique à

Load(IDataReader, LoadOption)

Source:
DataTable.cs
Source:
DataTable.cs
Source:
DataTable.cs

Remplit un DataTable avec des valeurs issues d'une source de données à l'aide du IDataReader fourni. Si DataTable contient déjà des lignes, les données entrantes à partir de la source de données sont fusionnées avec les lignes existantes en fonction de la valeur du paramètre 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)

Paramètres

reader
IDataReader

IDataReader qui fournit un ou plusieurs jeux de résultats.

loadOption
LoadOption

Valeur issue de l'énumération LoadOption qui indique comment les lignes déjà présentes dans le DataTable sont associées aux lignes entrantes qui partagent la même clé primaire.

Exemples

L’exemple suivant illustre plusieurs des problèmes liés à l’appel de la Load méthode . Tout d’abord, l’exemple se concentre sur les problèmes de schéma, notamment la déduction d’un schéma à partir du chargé IDataReader, puis la gestion des schémas incompatibles et des schémas avec des colonnes manquantes ou supplémentaires. L’exemple se concentre ensuite sur les problèmes de données, y compris la gestion des différentes options de chargement.

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

Remarques

La Load méthode utilise le premier jeu de résultats à partir du chargé IDataReaderet, une fois l’exécution réussie, définit la position du lecteur sur le jeu de résultats suivant, le cas échéant. Lors de la conversion de données, la Load méthode utilise les mêmes règles de conversion que la Fill méthode .

La Load méthode doit prendre en compte trois problèmes spécifiques lors du chargement des données à partir d’un IDataReader instance : schéma, données et opérations d’événement. Lors de l’utilisation du schéma, la Load méthode peut rencontrer des conditions comme décrit dans le tableau suivant. Les opérations de schéma ont lieu pour tous les jeux de résultats importés, même ceux qui ne contiennent pas de données.

Condition Comportement
le n’a pas de DataTable schéma. La Load méthode déduit le schéma en fonction du jeu de résultats de l’importé IDataReader.
a DataTable un schéma, mais il n’est pas compatible avec le schéma chargé. La Load méthode lève une exception correspondant à l’erreur particulière qui se produit lors de la tentative de chargement de données dans le schéma incompatible.
Les schémas sont compatibles, mais le schéma du jeu de résultats chargé contient des colonnes qui n’existent pas dans .DataTable La Load méthode ajoute les colonnes supplémentaires au DataTableschéma de . La méthode lève une exception si les colonnes correspondantes dans et DataTable le jeu de résultats chargé ne sont pas compatibles avec la valeur. La méthode récupère également les informations de contrainte du jeu de résultats pour toutes les colonnes ajoutées. À l’exception de la contrainte clé primaire, ces informations de contrainte sont utilisées uniquement si le courant DataTable ne contient pas de colonnes au début de l’opération de chargement.
Les schémas sont compatibles, mais le schéma du jeu de résultats chargé contient moins de colonnes que le DataTable. Si une colonne manquante a une valeur par défaut définie ou si le type de données de la colonne est nullable, la Load méthode permet d’ajouter les lignes, en remplaçant la valeur par défaut ou null par la colonne manquante. Si aucune valeur par défaut ou null ne peut être utilisée, la Load méthode lève une exception. Si aucune valeur par défaut spécifique n’a été fournie, la Load méthode utilise la valeur null comme valeur par défaut implicite.

Avant d’envisager le comportement de la Load méthode en termes d’opérations de données, considérez que chaque ligne d’un DataTable conserve à la fois la valeur actuelle et la valeur d’origine pour chaque colonne. Ces valeurs peuvent être équivalentes ou différentes si les données de la ligne ont été modifiées depuis le remplissage de .DataTable Pour plus d’informations , consultez États des lignes et Versions de ligne .

Dans cet appel de méthode, le paramètre spécifié LoadOption influence le traitement des données entrantes. Comment la méthode Load doit-elle gérer le chargement des lignes qui ont la même clé primaire que les lignes existantes ? Doit-il modifier les valeurs actuelles, les valeurs d’origine ou les deux ? Ces problèmes, et bien plus encore, sont contrôlés par le loadOption paramètre .

Si la ligne existante et la ligne entrante contiennent des valeurs de clé primaire correspondantes, la ligne est traitée à l’aide de sa valeur d’état de ligne actuelle, sinon elle est traitée comme une nouvelle ligne.

En termes d’opérations d’événement, l’événement RowChanging se produit avant que chaque ligne ne soit modifiée, et l’événement RowChanged se produit après chaque ligne a été modifiée. Dans chaque cas, la Action propriété de l’instance DataRowChangeEventArgs passée au gestionnaire d’événements contient des informations sur l’action particulière associée à l’événement. Cette valeur d’action varie en fonction de l’état de la ligne avant l’opération de chargement. Dans chaque cas, les deux événements se produisent et l’action est la même pour chacun d’eux. L’action peut être appliquée à la version actuelle ou à la version d’origine de chaque ligne, ou aux deux, en fonction de l’état actuel de la ligne.

Le tableau suivant affiche le comportement de la méthode Load lorsqu’elle est appelée avec chacune des LoadOption valeurs, et montre également comment les valeurs interagissent avec l’état de la ligne pour la ligne en cours de chargement. La dernière ligne (intitulée « (Non présent) ») décrit le comportement des lignes entrantes qui ne correspondent à aucune ligne existante. Chaque cellule de ce tableau décrit la valeur actuelle et la valeur d’origine d’un champ dans une ligne, ainsi que la DataRowState valeur pour la valeur une fois la Load méthode terminée.

DataRowState existant Upsert OverwriteChanges PreserveChanges (comportement par défaut)
Ajout Current = <Entrant>

Original = -<Non disponible>

État = <Ajouté>

RowAction = Change
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Existant>

Original = <Entrant>

État = <Modifié>

RowAction = ChangeOriginal
Modifié le Current = <Entrant>

Original = <Existant>

État = <Modifié>

RowAction = Change
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Existant>

Original = <Entrant>

État = <Modifié>

RowAction =ChangeOriginal
Deleted (Le chargement n’affecte pas les lignes supprimées)

Current = ---

Original = <Existant>

État = <Supprimé>

(Une nouvelle ligne est ajoutée avec les caractéristiques suivantes)

Current = <Entrant>

Original = <Non disponible>

État = <Ajouté>

RowAction = Ajouter
Annuler la suppression et

Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Non disponible>

Original = <Entrant>

État = <Supprimé>

RowAction = ChangeOriginal
Inchangé Current = <Entrant>

Original = <Existant>

Si la nouvelle valeur est identique à la valeur existante,

État = <Inchangé>

RowAction = Nothing

Else

État = <Modifié>

RowAction = Change
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Non présent) Current = <Entrant>

Original = <Non disponible>

État = <Ajouté>

RowAction = Ajouter
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal

Les valeurs d’un DataColumn peuvent être limitées par l’utilisation de propriétés telles que ReadOnly et AutoIncrement. La Load méthode gère ces colonnes d’une manière cohérente avec le comportement défini par les propriétés de la colonne. La contrainte en lecture seule sur un DataColumn s’applique uniquement aux modifications qui se produisent dans la mémoire. Si Load nécessaire, la méthode remplace les valeurs de colonne en lecture seule.

Si vous spécifiez les options OverwriteChanges ou PreserveChanges lors de l’appel de la Load méthode, on suppose que les données entrantes proviennent de la DataTablesource de données primaire et que le DataTable suit les modifications et peut propager les modifications à la source de données. Si vous sélectionnez l’option Upsert, il est supposé que les données proviennent d’une source de données secondaire, telle que les données fournies par un composant de niveau intermédiaire, éventuellement modifiées par un utilisateur. Dans ce cas, l’hypothèse est que l’intention est d’agréger des données d’une ou de plusieurs sources de données dans le DataTable, puis de propager éventuellement les données à la source de données primaire. Le LoadOption paramètre est utilisé pour déterminer la version spécifique de la ligne à utiliser pour la comparaison de clé primaire. Le tableau ci-dessous fournit les détails.

Option Charger Version de DataRow utilisée pour la comparaison de clé primaire
OverwriteChanges Version d’origine, si elle existe, sinon Version actuelle
PreserveChanges Version d’origine, si elle existe, sinon Version actuelle
Upsert Version actuelle, si elle existe, sinon version d’origine

Voir aussi

S’applique à

Load(IDataReader, LoadOption, FillErrorEventHandler)

Source:
DataTable.cs
Source:
DataTable.cs
Source:
DataTable.cs

Remplit un DataTable avec des valeurs issues d'une source de données à l'aide du IDataReader fourni et d'un délégué de gestion d'erreur.

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)

Paramètres

reader
IDataReader

Un IDataReader qui fournit un jeu de résultats.

loadOption
LoadOption

Valeur issue de l'énumération LoadOption qui indique comment les lignes déjà présentes dans le DataTable sont associées aux lignes entrantes qui partagent la même clé primaire.

errorHandler
FillErrorEventHandler

Un délégué FillErrorEventHandler à appeler lorsqu'une erreur se produit en chargeant des données.

Exemples

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

Remarques

La Load méthode utilise le premier jeu de résultats à partir du chargé IDataReaderet, une fois l’exécution réussie, définit la position du lecteur sur le jeu de résultats suivant, le cas échéant. Lors de la conversion de données, la Load méthode utilise les mêmes règles de conversion que la DbDataAdapter.Fill méthode .

La Load méthode doit prendre en compte trois problèmes spécifiques lors du chargement des données à partir d’un IDataReader instance : schéma, données et opérations d’événement. Lors de l’utilisation du schéma, la Load méthode peut rencontrer des conditions comme décrit dans le tableau suivant. Les opérations de schéma ont lieu pour tous les jeux de résultats importés, même ceux qui ne contiennent pas de données.

Condition Comportement
le n’a pas de DataTable schéma. La Load méthode déduit le schéma en fonction du jeu de résultats de l’importé IDataReader.
a DataTable un schéma, mais il n’est pas compatible avec le schéma chargé. La Load méthode lève une exception correspondant à l’erreur particulière qui se produit lors de la tentative de chargement de données dans le schéma incompatible.
Les schémas sont compatibles, mais le schéma du jeu de résultats chargé contient des colonnes qui n’existent pas dans .DataTable La Load méthode ajoute la ou les colonnes supplémentaires au DataTableschéma de . La méthode lève une exception si les colonnes correspondantes dans et DataTable le jeu de résultats chargé ne sont pas compatibles avec la valeur. La méthode récupère également les informations de contrainte du jeu de résultats pour toutes les colonnes ajoutées. À l’exception de la contrainte clé primaire, ces informations de contrainte sont utilisées uniquement si le courant DataTable ne contient pas de colonnes au début de l’opération de chargement.
Les schémas sont compatibles, mais le schéma du jeu de résultats chargé contient moins de colonnes que le DataTable. Si une colonne manquante a une valeur par défaut définie ou si le type de données de la colonne est nullable, la Load méthode permet d’ajouter les lignes, en remplaçant la valeur par défaut ou null par la colonne manquante. Si aucune valeur par défaut ou null ne peut être utilisée, la Load méthode lève une exception. Si aucune valeur par défaut spécifique n’a été fournie, la Load méthode utilise la valeur null comme valeur par défaut implicite.

Avant d’envisager le comportement de la Load méthode en termes d’opérations de données, considérez que chaque ligne d’un DataTable conserve à la fois la valeur actuelle et la valeur d’origine pour chaque colonne. Ces valeurs peuvent être équivalentes ou différentes si les données de la ligne ont été modifiées depuis le remplissage de .DataTable Pour plus d’informations , consultez États des lignes et Versions de ligne .

Dans cet appel de méthode, le paramètre spécifié LoadOption influence le traitement des données entrantes. Comment la méthode Load doit-elle gérer le chargement des lignes qui ont la même clé primaire que les lignes existantes ? Doit-il modifier les valeurs actuelles, les valeurs d’origine ou les deux ? Ces problèmes, et bien plus encore, sont contrôlés par le loadOption paramètre .

Si la ligne existante et la ligne entrante contiennent des valeurs de clé primaire correspondantes, la ligne est traitée à l’aide de sa valeur d’état de ligne actuelle, sinon elle est traitée comme une nouvelle ligne.

En termes d’opérations d’événement, l’événement RowChanging se produit avant que chaque ligne ne soit modifiée, et l’événement RowChanged se produit après chaque ligne a été modifiée. Dans chaque cas, la Action propriété de l’instance DataRowChangeEventArgs passée au gestionnaire d’événements contient des informations sur l’action particulière associée à l’événement. Cette valeur d’action varie en fonction de l’état de la ligne avant l’opération de chargement. Dans chaque cas, les deux événements se produisent et l’action est la même pour chacun d’eux. L’action peut être appliquée à la version actuelle ou à la version d’origine de chaque ligne, ou aux deux, en fonction de l’état actuel de la ligne.

Le tableau suivant affiche le comportement de la méthode Load lorsqu’elle est appelée avec chacune des LoadOption valeurs, et montre également comment les valeurs interagissent avec l’état de la ligne pour la ligne en cours de chargement. La dernière ligne (intitulée « (Non présent) ») décrit le comportement des lignes entrantes qui ne correspondent à aucune ligne existante. Chaque cellule de ce tableau décrit la valeur actuelle et la valeur d’origine d’un champ dans une ligne, ainsi que la DataRowState valeur pour la valeur une fois la Load méthode terminée.

DataRowState existant Upsert OverwriteChanges PreserveChanges (comportement par défaut)
Ajout Current = <Entrant>

Original = -<Non disponible>

État = <Ajouté>

RowAction = Change
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Existant>

Original = <Entrant>

État = <Modifié>

RowAction = ChangeOriginal
Modifié le Current = <Entrant>

Original = <Existant>

État = <Modifié>

RowAction = Change
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Existant>

Original = <Entrant>

État = <Modifié>

RowAction =ChangeOriginal
supprimé (La charge n’affecte pas les lignes supprimées)

Current = ---

Original = <Existant>

État = <Supprimé>

(Une nouvelle ligne est ajoutée avec les caractéristiques suivantes)

Current = <Entrant>

Original = <Non disponible>

État = <Ajouté>

RowAction = Add
Annuler la suppression et

Current = <Entrant>

Original = <Entrant>

État = <inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Non disponible>

Original = <Entrant>

État = <Supprimé>

RowAction = ChangeOriginal
Inchangé Current = <Entrant>

Original = <Existant>

Si la nouvelle valeur est identique à la valeur existante, alors

État = <inchangé>

RowAction = Nothing

Else

État = <Modifié>

RowAction = Change
Current = <Entrant>

Original = <Entrant>

État = <inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Entrant>

Original = <Entrant>

État = <inchangé>

RowAction = ChangeCurrentAndOriginal
Non présent) Current = <Entrant>

Original = <Non disponible>

État = <Ajouté>

RowAction = Add
Current = <Entrant>

Original = <Entrant>

État = <inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Entrant>

Original = <Entrant>

État = <inchangé>

RowAction = ChangeCurrentAndOriginal

Les valeurs d’un DataColumn peuvent être limitées par l’utilisation de propriétés telles que ReadOnly et AutoIncrement. La Load méthode gère ces colonnes d’une manière cohérente avec le comportement défini par les propriétés de la colonne. La contrainte en lecture seule sur un DataColumn s’applique uniquement aux modifications qui se produisent dans la mémoire. Si Load nécessaire, la méthode remplace les valeurs de colonne en lecture seule.

Si vous spécifiez les options OverwriteChanges ou PreserveChanges lors de l’appel de la Load méthode, l’hypothèse est faite que les données entrantes proviennent de la DataTablesource de données primaire de , et le DataTable suit les modifications et peut propager les modifications à la source de données. Si vous sélectionnez l’option Upsert, il est supposé que les données proviennent d’une source de données secondaire, telle que les données fournies par un composant de niveau intermédiaire, peut-être modifiées par un utilisateur. Dans ce cas, l’hypothèse est que l’intention est d’agréger des données à partir d’une ou plusieurs sources de données dans le DataTable, puis peut-être de propager les données à la source de données primaire. Le LoadOption paramètre est utilisé pour déterminer la version spécifique de la ligne qui doit être utilisée pour la comparaison de clé primaire. Le tableau ci-dessous fournit les détails.

Option De chargement Version de DataRow utilisée pour la comparaison de clé primaire
OverwriteChanges Version d’origine, si elle existe, sinon Version actuelle
PreserveChanges Version d’origine, si elle existe, sinon Version actuelle
Upsert Version actuelle, si elle existe, sinon Version d’origine

Le errorHandler paramètre est un FillErrorEventHandler délégué qui fait référence à une procédure appelée lorsqu’une erreur se produit lors du chargement des données. Le FillErrorEventArgs paramètre passé à la procédure fournit des propriétés qui vous permettent de récupérer des informations sur l’erreur qui s’est produite, la ligne de données actuelle et le DataTable en cours de remplissage. L’utilisation de ce mécanisme de délégué, plutôt qu’un bloc try/catch plus simple, vous permet de déterminer l’erreur, de gérer la situation et de poursuivre le traitement si vous le souhaitez. Le FillErrorEventArgs paramètre fournit une Continue propriété : définissez cette propriété sur true pour indiquer que vous avez géré l’erreur et que vous souhaitez continuer le traitement. Définissez la propriété false sur pour indiquer que vous souhaitez arrêter le traitement. N’oubliez pas que si vous définissez la propriété sur false , le code qui a déclenché le problème lève une exception.

Voir aussi

S’applique à