Partager via


DataTable.Load Méthode

Définition

Remplit une DataTable valeur à partir d’une source de données à l’aide de l’élément fourni IDataReader. Si les DataTable lignes contiennent déjà, les données entrantes de la source de données sont fusionnées avec les lignes existantes.

Surcharges

Nom Description
Load(IDataReader)

Remplit une DataTable valeur à partir d’une source de données à l’aide de l’élément fourni IDataReader. Si les DataTable lignes contiennent déjà, les données entrantes de la source de données sont fusionnées avec les lignes existantes.

Load(IDataReader, LoadOption)

Remplit une DataTable valeur à partir d’une source de données à l’aide de l’élément fourni IDataReader. Si les DataTable lignes contiennent déjà, les données entrantes de la source de données sont fusionnées avec les lignes existantes en fonction de la valeur du loadOption paramètre.

Load(IDataReader, LoadOption, FillErrorEventHandler)

Remplit une DataTable valeur à partir d’une source de données à l’aide d’un délégué de gestion des erreurs fourni IDataReader .

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 l’inférence d’un schéma à partir du schéma 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, notamment la gestion des différentes options de chargement.

Note

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, centrée sur l’obtention de données à partir d’une source de données spécifiée et son ajout au conteneur de données actuel (dans ce cas, a DataTable). Ces scénarios décrivent l’utilisation standard pour un DataTable, décrivant son comportement de mise à jour et de fusion.

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

Étant donné ces deux sources de données hypothétiques, un utilisateur a probablement besoin de 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. Plus tard, 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 remplissage dans le scénario précédent et effectuer une synchronisation incrémentielle avec la source de données primaire, en préservant les modifications apportées dans le DataTable.

  • Flux de données incrémentiels provenant 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. L’une des surcharges de cette méthode vous permet de spécifier un paramètre d’option de chargement, indiquant comment les lignes déjà dans une DataTable combinaison avec les lignes chargées. (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) Met à jour la version d’origine de la ligne avec la valeur de la ligne entrante.
OverwriteChanges Met à jour les versions actuelles et d’origine de la ligne avec la valeur de la ligne entrante.
Upsert Met à jour la version actuelle de la ligne avec la valeur de la ligne entrante.

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

Load(IDataReader)

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

Remplit une DataTable valeur à partir d’une source de données à l’aide de l’élément fourni IDataReader. Si les DataTable lignes contiennent déjà, les données entrantes de la source de données sont fusionnées avec les lignes existantes.

public:
 void Load(System::Data::IDataReader ^ reader);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Members from types used in the expression column to be trimmed if not referenced directly.")]
public void Load(System.Data.IDataReader reader);
public void Load(System.Data.IDataReader reader);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Members from types used in the expression column to be trimmed if not referenced directly.")>]
member this.Load : System.Data.IDataReader -> unit
member this.Load : System.Data.IDataReader -> unit
Public Sub Load (reader As IDataReader)

Paramètres

reader
IDataReader

Qui IDataReader fournit un jeu de résultats.

Attributs

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 l’inférence d’un schéma à partir du schéma 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 utilise le premier jeu de résultats à partir du jeu de résultats chargé IDataReaderet, après la réussite de l’exécution, 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’une IDataReader instance : schéma, données et opérations d’événement. Lorsque vous utilisez le 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 contenant aucune donnée.

Pathologie Comportement
Le DataTable schéma n’a pas de schéma. La Load méthode déduit le schéma basé sur le jeu de résultats à partir de l’objet importé IDataReader.
Le DataTable schéma a 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. La méthode lève une exception si les colonnes correspondantes dans le jeu de DataTable 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 aucune colonne 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 que 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 ne null 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, considérez que chaque ligne d’une DataTable ligne conserve à la fois la valeur actuelle et la valeur d’origine pour chaque colonne. Ces valeurs peuvent être équivalentes ou peuvent être différentes si les données de la ligne ont été modifiées depuis le remplissage du DataTablefichier . Pour plus d’informations, consultez Les états de ligne et les versions de ligne.

Cette version de la Load méthode tente de conserver les valeurs actuelles dans chaque ligne, 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 la modification de chaque ligne et l’événement RowChanged se produit une fois que 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 originale de chaque ligne, ou les deux, en fonction de l’état actuel de la ligne.

Le tableau suivant affiche le comportement de la Load méthode. La ligne finale (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 la DataRowState 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é(e) Current = <Existing>

Original = <Entrant>

État = <Modifié>

RowAction = ChangeOriginal
Modifié Current = <Existing>

Original = <Entrant>

État = <Modifié>

RowAction = ChangeOriginal
Supprimé 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 objet DataColumn peuvent être contraintes par l’utilisation de propriétés telles que ReadOnly et AutoIncrement. La Load méthode gère ces colonnes de 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 est applicable uniquement aux modifications qui se produisent en mémoire. La Load méthode remplace les valeurs de colonne en lecture seule, si nécessaire.

Pour déterminer la version du champ de clé primaire à utiliser pour comparer la ligne actuelle à une ligne entrante, la Load méthode utilise la version d’origine de la valeur de clé primaire dans une ligne, s’il 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
Source:
DataTable.cs
Source:
DataTable.cs

Remplit une DataTable valeur à partir d’une source de données à l’aide de l’élément fourni IDataReader. Si les DataTable lignes contiennent déjà, les données entrantes de la source de données sont fusionnées avec les lignes existantes en fonction de la valeur du loadOption paramètre.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Using LoadOption may cause members from types used in the expression column to be trimmed if not referenced directly.")]
public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption);
public void Load(System.Data.IDataReader reader, System.Data.LoadOption loadOption);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Using LoadOption may cause members from types used in the expression column to be trimmed if not referenced directly.")>]
member this.Load : System.Data.IDataReader * System.Data.LoadOption -> unit
member this.Load : System.Data.IDataReader * System.Data.LoadOption -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption)

Paramètres

reader
IDataReader

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

loadOption
LoadOption

Valeur de l’énumération LoadOption qui indique comment les lignes déjà présentes sont DataTable combinées avec les lignes entrantes qui partagent la même clé primaire.

Attributs

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 l’inférence d’un schéma à partir du schéma 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, notamment 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 jeu de résultats chargé IDataReaderet, après la réussite de l’exécution, 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’une IDataReader instance : schéma, données et opérations d’événement. Lorsque vous utilisez le 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 contenant aucune donnée.

Pathologie Comportement
Le DataTable schéma n’a pas de schéma. La Load méthode déduit le schéma basé sur le jeu de résultats à partir de l’objet importé IDataReader.
Le DataTable schéma a 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. La méthode lève une exception si les colonnes correspondantes dans le jeu de DataTable 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 aucune colonne 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 que 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 pour 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’une DataTable ligne conserve à la fois la valeur actuelle et la valeur d’origine pour chaque colonne. Ces valeurs peuvent être équivalentes ou peuvent être différentes si les données de la ligne ont été modifiées depuis le remplissage du DataTablefichier . Pour plus d’informations, consultez États des lignes et versions de lignes .

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 la modification de chaque ligne et l’événement RowChanged se produit une fois que 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 originale de chaque ligne, ou les 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 valeurs, et montre également comment les valeurs interagissent avec l’état de LoadOption ligne du chargement de la ligne. La ligne finale (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 la DataRowState valeur une fois la Load méthode terminée.

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

Original = -<Non disponible>

État = <Ajouté>

RowAction = Modifier
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Entrant>

État = <Modifié>

RowAction = ChangeOriginal
Modifié Current = <Entrant>

Original = <Existant>

État = <Modifié>

RowAction = Modifier
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Entrant>

État = <Modifié>

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

Current = ---

Original = <Existant>

État = <Supprimé>

(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

Autre

État = <Modifié>

RowAction = Modifier
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 objet DataColumn peuvent être contraintes par l’utilisation de propriétés telles que ReadOnly et AutoIncrement. La Load méthode gère ces colonnes de 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 est applicable uniquement aux modifications qui se produisent en mémoire. La Load méthode remplace les valeurs de colonne en lecture seule, si nécessaire.

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 principale, et dataTable effectue le suivi des modifications et peuvent 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 d’une ou plusieurs sources de données dans le DataTable, puis 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 à utiliser pour la comparaison de clés primaires. Le tableau ci-dessous fournit les détails.

Option Charger Version de DataRow utilisée pour la comparaison de clés primaires
OverwriteChanges Version d’origine, s’il existe, sinon version actuelle
PreserveChanges Version d’origine, s’il existe, sinon version actuelle
Upsert Version actuelle, s’il existe, sinon version d’origine

Voir aussi

S’applique à

Load(IDataReader, LoadOption, FillErrorEventHandler)

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

Remplit une DataTable valeur à partir d’une source de données à l’aide d’un délégué de gestion des erreurs fourni IDataReader .

public:
 virtual void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, System::Data::FillErrorEventHandler ^ errorHandler);
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Using LoadOption may cause members from types used in the expression column to be trimmed if not referenced directly.")]
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);
[<System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Using LoadOption may cause members from types used in the expression column to be trimmed if not referenced directly.")>]
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
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

Qui IDataReader fournit un jeu de résultats.

loadOption
LoadOption

Valeur de l’énumération LoadOption qui indique comment les lignes déjà présentes sont DataTable combinées avec les lignes entrantes qui partagent la même clé primaire.

errorHandler
FillErrorEventHandler

Délégué FillErrorEventHandler à appeler lorsqu’une erreur se produit lors du chargement des données.

Attributs

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 jeu de résultats chargé IDataReaderet, après la réussite de l’exécution, 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’une IDataReader instance : schéma, données et opérations d’événement. Lorsque vous utilisez le 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 contenant aucune donnée.

Pathologie Comportement
Le DataTable schéma n’a pas de schéma. La Load méthode déduit le schéma basé sur le jeu de résultats à partir de l’objet importé IDataReader.
Le DataTable schéma a 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 la ou les colonnes supplémentaires au DataTableschéma. La méthode lève une exception si les colonnes correspondantes dans le jeu de DataTable 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 aucune colonne 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 que 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 pour 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’une DataTable ligne conserve à la fois la valeur actuelle et la valeur d’origine pour chaque colonne. Ces valeurs peuvent être équivalentes ou peuvent être différentes si les données de la ligne ont été modifiées depuis le remplissage du DataTablefichier . Pour plus d’informations, consultez États des lignes et versions de lignes .

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 la modification de chaque ligne et l’événement RowChanged se produit une fois que 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 originale de chaque ligne, ou les 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 valeurs, et montre également comment les valeurs interagissent avec l’état de LoadOption ligne du chargement de la ligne. La ligne finale (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 la DataRowState valeur une fois la Load méthode terminée.

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

Original = -<Non disponible>

État = <Ajouté>

RowAction = Modifier
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Entrant>

État = <Modifié>

RowAction = ChangeOriginal
Modifié Current = <Entrant>

Original = <Existant>

État = <Modifié>

RowAction = Modifier
Current = <Entrant>

Original = <Entrant>

État = <Inchangé>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Original = <Entrant>

État = <Modifié>

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

Current = ---

Original = <Existant>

État = <Supprimé>

(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

Autre

État = <Modifié>

RowAction = Modifier
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 objet DataColumn peuvent être contraintes par l’utilisation de propriétés telles que ReadOnly et AutoIncrement. La Load méthode gère ces colonnes de 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 est applicable uniquement aux modifications qui se produisent en mémoire. La Load méthode remplace les valeurs de colonne en lecture seule, si nécessaire.

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 principale, et dataTable effectue le suivi des modifications et peuvent 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 d’une ou plusieurs sources de données dans le DataTable, puis 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 à utiliser pour la comparaison de clés primaires. Le tableau ci-dessous fournit les détails.

Option Charger Version de DataRow utilisée pour la comparaison de clés primaires
OverwriteChanges Version d’origine, s’il existe, sinon version actuelle
PreserveChanges Version d’origine, s’il existe, sinon version actuelle
Upsert Version actuelle, s’il 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 actuelle de données et le DataTable remplissage. À l’aide 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 continuer à traiter si vous le souhaitez. Le FillErrorEventArgs paramètre fournit une Continue propriété : définissez cette propriété pour true indiquer que vous avez géré l’erreur et que vous souhaitez poursuivre le traitement. Définissez la propriété pour false indiquer que vous souhaitez arrêter le traitement. N’oubliez pas que la définition de la propriété provoque false le code qui a déclenché le problème pour lever une exception.

Voir aussi

S’applique à