DataTable.Load Metoda

Definicja

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . Jeśli już DataTable zawiera wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami.

Przeciążenia

Load(IDataReader)

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . Jeśli obiekt DataTable zawiera już wiersze, dane przychodzące ze źródła danych zostaną scalone z istniejącymi wierszami.

Load(IDataReader, LoadOption)

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . Jeśli obiekt DataTable zawiera już wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami zgodnie z wartością parametru loadOption .

Load(IDataReader, LoadOption, FillErrorEventHandler)

Wypełnia element DataTable wartościami ze źródła danych przy użyciu dostarczonego IDataReader delegata obsługującego błędy.

Przykłady

W poniższym przykładzie pokazano kilka problemów związanych z wywoływaniem Load metody . Najpierw przykład koncentruje się na problemach ze schematem, w tym wnioskowaniu schematu z załadowanych IDataReaderschematów, a następnie obsłudze niezgodnych schematów i schematów z brakującymi lub dodatkowymi kolumnami. Następnie przykład koncentruje się na problemach z danymi, w tym obsłudze różnych opcji ładowania.

Uwaga

W tym przykładzie pokazano, jak używać jednej z przeciążonych wersji programu Load. Inne przykłady, które mogą być dostępne, można znaleźć w poszczególnych tematach przeciążenia.

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

Uwagi

Metoda Load może być używana w kilku typowych scenariuszach— wszystkie skupione wokół pobierania danych z określonego źródła danych i dodawania ich do bieżącego kontenera danych (w tym przypadku ).DataTable W tych scenariuszach opisano standardowe użycie elementu DataTable, opisującego jego zachowanie aktualizacji i scalania.

Element DataTable synchronizuje lub aktualizuje jedno podstawowe źródło danych. Śledzi DataTable zmiany, umożliwiając synchronizację z podstawowym źródłem danych. Ponadto obiekt DataTable może akceptować przyrostowe dane z co najmniej jednego pomocniczego źródła danych. Element DataTable nie jest odpowiedzialny za śledzenie zmian w celu umożliwienia synchronizacji z pomocniczym źródłem danych.

Biorąc pod uwagę te dwa hipotetyczne źródła danych, użytkownik może wymagać jednego z następujących zachowań:

  • Inicjowanie DataTable z podstawowego źródła danych. W tym scenariuszu użytkownik chce zainicjować pusty DataTable element z wartościami z podstawowego źródła danych. Później użytkownik zamierza propagować zmiany z powrotem do podstawowego źródła danych.

  • Zachowaj zmiany i ponownie zsynchronizuj je z podstawowego źródła danych. W tym scenariuszu użytkownik chce wykonać wypełnioną DataTable w poprzednim scenariuszu synchronizację przyrostową z podstawowym źródłem danych, zachowując modyfikacje wprowadzone w pliku DataTable.

  • Przyrostowe źródło danych z pomocniczych źródeł danych. W tym scenariuszu użytkownik chce scalić zmiany z co najmniej jednego pomocniczego źródła danych i propagować te zmiany z powrotem do podstawowego źródła danych.

Metoda Load umożliwia wykonanie wszystkich tych scenariuszy. Wszystkie, ale jedno z przeciążeń dla tej metody umożliwia określenie parametru opcji ładowania, wskazując, jak wiersze już w DataTable połączeniu z wierszami są ładowane. (Przeciążenie, które nie umożliwia określenia zachowania używa domyślnej opcji ładowania). W poniższej tabeli opisano trzy opcje ładowania udostępniane przez wyliczenie LoadOption . W każdym przypadku opis wskazuje zachowanie, gdy klucz podstawowy wiersza w danych przychodzących jest zgodny z kluczem podstawowym istniejącego wiersza.

Opcja ładowania Opis
PreserveChanges (domyślne) Aktualizacje oryginalną wersję wiersza z wartością wiersza przychodzącego.
OverwriteChanges Aktualizacje bieżące i oryginalne wersje wiersza z wartością wiersza przychodzącego.
Upsert Aktualizacje bieżącą wersję wiersza z wartością wiersza przychodzącego.

Ogólnie rzecz biorąc, opcje i OverwriteChanges są przeznaczone dla scenariuszy, PreserveChanges w których użytkownik musi zsynchronizować DataSet zmiany i z podstawowym źródłem danych. Opcja Upsert ułatwia agregowanie zmian z co najmniej jednego pomocniczego źródła danych.

Load(IDataReader)

Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . Jeśli obiekt DataTable zawiera już wiersze, dane przychodzące ze źródła danych zostaną scalone z istniejącymi wierszami.

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)

Parametry

reader
IDataReader

Element IDataReader , który udostępnia zestaw wyników.

Przykłady

W poniższym przykładzie pokazano kilka problemów związanych z wywoływaniem Load metody . Najpierw przykład koncentruje się na problemach ze schematem, w tym wnioskowaniu schematu z załadowanych IDataReaderschematów, a następnie obsłudze niezgodnych schematów i schematów z brakującymi lub dodatkowymi kolumnami. Następnie przykład wywołuje metodę Load , wyświetlając dane zarówno przed, jak i po operacji ładowania.

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

Uwagi

Metoda Load używa pierwszego zestawu wyników z załadowanego IDataReaderzestawu , a po pomyślnym zakończeniu ustawia pozycję czytelnika na następny zestaw wyników, jeśli istnieje. Podczas konwertowania Load danych metoda używa tych samych reguł konwersji co DbDataAdapter.Fill metoda .

Metoda Load musi uwzględniać trzy konkretne problemy podczas ładowania danych z IDataReader wystąpienia: schematu, danych i operacji zdarzeń. Podczas pracy ze schematem Load metoda może napotkać warunki, zgodnie z opisem w poniższej tabeli. Operacje schematu są wykonywane dla wszystkich zaimportowanych zestawów wyników, nawet tych, które nie zawierają żadnych danych.

Warunek Zachowanie
Element DataTable nie ma schematu. Metoda Load wnioskuje schemat na podstawie zestawu wyników z zaimportowanego IDataReaderelementu .
Element DataTable ma schemat, ale jest niezgodny z załadowanym schematem. Metoda Load zgłasza wyjątek odpowiadający konkretnemu błędowi, który występuje podczas próby załadowania danych do niezgodnego schematu.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera kolumny, które nie istnieją w obiekcie DataTable. Metoda Load dodaje dodatkowe kolumny do DataTableschematu . Metoda zgłasza wyjątek, jeśli odpowiednie kolumny w DataTable obiekcie i załadowany zestaw wyników nie są zgodne z wartością. Metoda pobiera również informacje o ograniczeniu z zestawu wyników dla wszystkich dodanych kolumn. Z wyjątkiem ograniczenia klucza podstawowego, te informacje ograniczenia są używane tylko wtedy, gdy bieżący DataTable nie zawiera żadnych kolumn na początku operacji ładowania.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera mniej kolumn niż .DataTable Jeśli brakująca kolumna ma zdefiniowaną wartość domyślną lub typ danych kolumny ma wartość null, Load metoda umożliwia dodawanie wierszy, podstawianie wartości domyślnej lub null wartości brakującej kolumny. Jeśli nie ma wartości domyślnej lub null można jej użyć, Load metoda zgłasza wyjątek. Jeśli nie podano określonej wartości domyślnej, Load metoda używa null wartości jako wartości domyślnej.

Przed rozważeniem zachowania Load metody w zakresie operacji na danych należy wziąć pod uwagę, że każdy wiersz w obiekcie DataTable utrzymuje zarówno bieżącą wartość, jak i oryginalną wartość dla każdej kolumny. Te wartości mogą być równoważne lub mogą być inne, jeśli dane w wierszu zostały zmienione od czasu wypełnienia .DataTable Aby uzyskać więcej informacji, zobacz Stany wierszy i Wersje wierszy.

Ta wersja Load metody próbuje zachować bieżące wartości w każdym wierszu, pozostawiając oryginalną wartość nienaruszoną. (Jeśli chcesz mieć dokładnszą kontrolę nad zachowaniem danych przychodzących, zobacz DataTable.Load. Jeśli istniejący wiersz i wiersz przychodzący zawierają odpowiednie wartości klucza podstawowego, wiersz jest przetwarzany przy użyciu bieżącej wartości stanu wiersza, w przeciwnym razie jest traktowany jako nowy wiersz.

Jeśli chodzi o operacje na zdarzeniach, RowChanging zdarzenie występuje przed zmianą każdego wiersza, a RowChanged zdarzenie występuje po zmianie każdego wiersza. W każdym przypadku Action właściwość DataRowChangeEventArgs wystąpienia przekazanego do programu obsługi zdarzeń zawiera informacje o określonej akcji skojarzonej ze zdarzeniem. Ta wartość akcji zależy od stanu wiersza przed operacją ładowania. W każdym przypadku występują oba zdarzenia, a akcja jest taka sama dla każdego z nich. Akcja może być stosowana do bieżącej lub oryginalnej wersji każdego wiersza lub obu tych elementów w zależności od bieżącego stanu wiersza.

W poniższej Load tabeli przedstawiono zachowanie metody . Ostatni wiersz (oznaczony etykietą "(Nie ma)") opisuje zachowanie dla wierszy przychodzących, które nie pasują do żadnego istniejącego wiersza. Każda komórka w tej tabeli opisuje bieżącą i oryginalną wartość pola w wierszu wraz z DataRowState wartością dla po zakończeniu Load metody. W takim przypadku metoda nie zezwala na wskazanie opcji ładowania i używa wartości domyślnej PreserveChanges.

Istniejący stan DataRowState Wartości po Load metodzie i akcji zdarzenia
Dodane Current = <Istniejący>

Oryginalny = <przychodzący>

State = <Modified>

RowAction = ChangeOriginal
Zmodyfikowano Current = <Istniejący>

Oryginalny = <przychodzący>

State = <Modified>

RowAction = ChangeOriginal
Usunięte Current = <niedostępny>

Oryginalny = <przychodzący>

State = <Deleted>

RowAction = ChangeOriginal
Niezmienione Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <bez zmian>

RowAction = ChangeCurrentAndOriginal
(Nie ma) Current = <Przychodzące>

Oryginalny = <przychodzący>

Stan = <bez zmian>

RowAction = ChangeCurrentAndOriginal

Wartości w obiekcie DataColumn mogą być ograniczone za pomocą właściwości, takich jak ReadOnly i AutoIncrement. Metoda Load obsługuje takie kolumny w sposób zgodny z zachowaniem zdefiniowanym przez właściwości kolumny. Ograniczenie tylko do odczytu dla klasy DataColumn ma zastosowanie tylko w przypadku zmian występujących w pamięci. W Load razie potrzeby metoda zastępuje wartości kolumn tylko do odczytu.

Aby określić, która wersja pola klucza podstawowego ma być używana do porównywania bieżącego wiersza z wierszem przychodzącym, Load metoda używa oryginalnej wersji wartości klucza podstawowego w wierszu, jeśli istnieje. Load W przeciwnym razie metoda używa bieżącej wersji pola klucza podstawowego.

Zobacz też

Dotyczy

Load(IDataReader, LoadOption)

Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReaderelementu . DataTable Jeśli już zawiera wiersze, dane przychodzące ze źródła danych są scalane z istniejącymi wierszami zgodnie z wartością parametruloadOption.

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)

Parametry

reader
IDataReader

Element IDataReader , który udostępnia co najmniej jeden zestaw wyników.

loadOption
LoadOption

Wartość z LoadOption wyliczenia, która wskazuje, jak wiersze już w DataTable tabeli są łączone z wierszami przychodzącymi, które współużytkują ten sam klucz podstawowy.

Przykłady

W poniższym przykładzie pokazano kilka problemów związanych z wywoływaniem Load metody . Najpierw przykład koncentruje się na problemach ze schematem, w tym wnioskowaniu schematu z załadowanych IDataReaderschematów, a następnie obsłudze niezgodnych schematów i schematów z brakującymi lub dodatkowymi kolumnami. Następnie przykład koncentruje się na problemach z danymi, w tym obsłudze różnych opcji ładowania.

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

Uwagi

Metoda Load używa pierwszego zestawu wyników z załadowanego IDataReaderzestawu wyników, a po pomyślnym zakończeniu ustawia pozycję czytelnika na następny zestaw wyników, jeśli istnieje. Podczas konwertowania danych Load metoda używa tych samych reguł konwersji co Fill metoda.

Metoda Load musi uwzględniać trzy konkretne problemy podczas ładowania danych z IDataReader wystąpienia: schematu, danych i operacji zdarzeń. Podczas pracy ze schematem Load metoda może napotkać warunki zgodnie z opisem w poniższej tabeli. Operacje schematu są wykonywane dla wszystkich zaimportowanych zestawów wyników, nawet tych, które nie zawierają żadnych danych.

Warunek Zachowanie
Element DataTable nie ma schematu. Metoda Load wywnioskuje schemat na podstawie zestawu wyników z zaimportowanego IDataReaderelementu .
Element DataTable ma schemat, ale jest niezgodny z załadowanym schematem. Metoda Load zgłasza wyjątek odpowiadający określonemu błędowi, który występuje podczas próby załadowania danych do niezgodnego schematu.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera kolumny, które nie istnieją w obiekcie DataTable. Metoda Load dodaje dodatkowe kolumny do DataTableschematu . Metoda zgłasza wyjątek, jeśli odpowiednie kolumny w DataTable zestawie wyników i załadowany zestaw wyników nie są zgodne z wartością. Metoda pobiera również informacje o ograniczeniach z zestawu wyników dla wszystkich dodanych kolumn. Z wyjątkiem przypadku ograniczenia klucza podstawowego te informacje ograniczenia są używane tylko wtedy, gdy bieżący DataTable nie zawiera żadnych kolumn na początku operacji ładowania.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera mniej kolumn niż DataTable. Jeśli brak kolumny ma zdefiniowaną wartość domyślną lub typ danych kolumny ma wartość null, Load metoda umożliwia dodanie wierszy, zastąpienie wartości domyślnej lub null brakującej kolumny. Jeśli nie można użyć wartości domyślnej lub wartości null, Load metoda zgłasza wyjątek. Jeśli nie podano określonej wartości domyślnej, Load metoda używa wartości null jako dorozumianej wartości domyślnej.

Przed rozważeniem zachowania Load metody w zakresie operacji danych należy wziąć pod uwagę, że każdy wiersz w obrębie elementu DataTable zachowuje zarówno bieżącą wartość, jak i oryginalną wartość dla każdej kolumny. Te wartości mogą być równoważne lub mogą być inne, jeśli dane w wierszu zostały zmienione od czasu wypełnienia elementu DataTable. Aby uzyskać więcej informacji, zobacz Stany wierszy i wersje wierszy .

W tym wywołaniu metody określony LoadOption parametr wpływa na przetwarzanie danych przychodzących. Jak metoda Load powinna obsługiwać ładowanie wierszy, które mają ten sam klucz podstawowy co istniejące wiersze? Czy należy zmodyfikować bieżące wartości, oryginalne wartości lub oba te wartości? Te problemy i nie tylko są kontrolowane przez loadOption parametr .

Jeśli istniejący wiersz i wiersz przychodzący zawierają odpowiednie wartości klucza podstawowego, wiersz jest przetwarzany przy użyciu bieżącej wartości stanu wiersza, w przeciwnym razie jest traktowany jako nowy wiersz.

Jeśli chodzi o operacje zdarzenia, RowChanging zdarzenie występuje przed zmianą każdego wiersza, a RowChanged zdarzenie występuje po zmianie każdego wiersza. W każdym przypadku Action właściwość wystąpienia przekazanego DataRowChangeEventArgs do programu obsługi zdarzeń zawiera informacje o określonej akcji skojarzonej ze zdarzeniem. Ta wartość akcji różni się w zależności od stanu wiersza przed operacją ładowania. W każdym przypadku występują oba zdarzenia, a akcja jest taka sama dla każdego z nich. Akcja może być stosowana do bieżącej lub oryginalnej wersji każdego wiersza lub obu tych elementów w zależności od bieżącego stanu wiersza.

W poniższej tabeli przedstawiono zachowanie metody Load po wywołaniu z każdą z LoadOption wartości, a także pokazano, jak wartości wchodzą w interakcję ze stanem wiersza dla ładowanego wiersza. Ostatni wiersz (oznaczony etykietą "(Nie ma)") opisuje zachowanie dla wierszy przychodzących, które nie pasują do żadnego istniejącego wiersza. Każda komórka w tej tabeli opisuje bieżącą i oryginalną wartość pola w wierszu wraz z DataRowState wartością dla wartości po zakończeniu Load metody.

Istniejąca dataRowState Upsert Overwritechanges PreserveChanges (zachowanie domyślne)
Dodane Current = <Przychodzące>

Oryginalny = -<Niedostępny>

State = Added (Stan = Dodano) <>

RowAction = Zmiana
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Oryginał = <przychodzące>

State = Modified (Stan = <Zmodyfikowane)>

RowAction = ChangeOriginal
Zmodyfikowano Current = <Przychodzące>

Oryginalny = <istniejący>

State = Modified (Stan = <Zmodyfikowane)>

RowAction = Zmiana
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Oryginał = <przychodzące>

State = Modified (Stan = <Zmodyfikowane)>

RowAction =ChangeOriginal
Usunięte (Ładowanie nie ma wpływu na usunięte wiersze)

Current = ---

Oryginalny = <istniejący>

Stan = <Usunięto>

(Nowy wiersz jest dodawany z następującymi cechami)

Current = <Przychodzące>

Oryginalny = <niedostępny>

State = Added (Stan = Dodano) <>

RowAction = Dodaj
Cofnij usuwanie i

Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Niedostępne>

Oryginał = <przychodzące>

Stan = <Usunięto>

RowAction = ChangeOriginal
Niezmienione Current = <Przychodzące>

Oryginalny = <istniejący>

Jeśli nowa wartość jest taka sama jak istniejąca wartość, wówczas

State = <Bez zmian>

RowAction = Nic

Innego

State = Modified (Stan = <Zmodyfikowane)>

RowAction = Zmiana
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Brak obecności) Current = <Przychodzące>

Oryginalny = <niedostępny>

State = Added (Stan = Dodano) <>

RowAction = Dodaj
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal

Wartości w obiekcie DataColumn mogą być ograniczone za pomocą właściwości, takich jak ReadOnly i AutoIncrement. Metoda Load obsługuje takie kolumny w sposób zgodny z zachowaniem zdefiniowanym przez właściwości kolumny. Ograniczenie tylko do odczytu w obiekcie DataColumn ma zastosowanie tylko w przypadku zmian występujących w pamięci. W Load razie potrzeby metoda zastępuje wartości kolumn tylko do odczytu.

Jeśli podczas wywoływania Load metody określisz opcje OverwriteChanges lub PreserveChanges, zakłada się, że dane przychodzące pochodzą z podstawowego DataTableźródła danych, a tabela DataTable śledzi zmiany i może propagować zmiany z powrotem do źródła danych. Jeśli wybierzesz opcję Upsert, zakłada się, że dane pochodzą z jednego z pomocniczych źródeł danych, takich jak dane dostarczone przez składnik warstwy środkowej, być może zmienione przez użytkownika. W takim przypadku założeniem jest to, że celem jest agregowanie danych z co najmniej jednego źródła danych w obiekcie DataTable, a następnie propagowanie danych z powrotem do podstawowego źródła danych. Parametr LoadOption służy do określania określonej wersji wiersza, który ma być używany do porównania klucza podstawowego. Poniższa tabela zawiera szczegółowe informacje.

Opcja ładowania Wersja DataRow używana do porównania klucza podstawowego
OverwriteChanges Oryginalna wersja, jeśli istnieje, w przeciwnym razie bieżąca wersja
PreserveChanges Oryginalna wersja, jeśli istnieje, w przeciwnym razie bieżąca wersja
Upsert Bieżąca wersja, jeśli istnieje, w przeciwnym razie oryginalna wersja

Zobacz też

Dotyczy

Load(IDataReader, LoadOption, FillErrorEventHandler)

Źródło:
DataTable.cs
Źródło:
DataTable.cs
Źródło:
DataTable.cs

Wypełnia element DataTable wartościami ze źródła danych przy użyciu podanego IDataReader delegata obsługi błędów.

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)

Parametry

reader
IDataReader

Element IDataReader , który udostępnia zestaw wyników.

loadOption
LoadOption

Wartość z LoadOption wyliczenia, która wskazuje, jak wiersze już w DataTable tabeli są łączone z wierszami przychodzącymi, które współużytkują ten sam klucz podstawowy.

errorHandler
FillErrorEventHandler

Delegat FillErrorEventHandler do wywołania, gdy wystąpi błąd podczas ładowania danych.

Przykłady

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

Uwagi

Metoda Load używa pierwszego zestawu wyników z załadowanego IDataReaderzestawu wyników, a po pomyślnym zakończeniu ustawia pozycję czytelnika na następny zestaw wyników, jeśli istnieje. Podczas konwertowania danych Load metoda używa tych samych reguł konwersji co DbDataAdapter.Fill metoda.

Metoda Load musi uwzględniać trzy konkretne problemy podczas ładowania danych z IDataReader wystąpienia: schematu, danych i operacji zdarzeń. Podczas pracy ze schematem Load metoda może napotkać warunki zgodnie z opisem w poniższej tabeli. Operacje schematu są wykonywane dla wszystkich zaimportowanych zestawów wyników, nawet tych, które nie zawierają żadnych danych.

Warunek Zachowanie
Element DataTable nie ma schematu. Metoda Load wywnioskuje schemat na podstawie zestawu wyników z zaimportowanego IDataReaderelementu .
Element DataTable ma schemat, ale jest niezgodny z załadowanym schematem. Metoda Load zgłasza wyjątek odpowiadający określonemu błędowi, który występuje podczas próby załadowania danych do niezgodnego schematu.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera kolumny, które nie istnieją w obiekcie DataTable. Metoda Load dodaje dodatkowe kolumny do DataTableschematu . Metoda zgłasza wyjątek, jeśli odpowiednie kolumny w DataTable zestawie wyników i załadowany zestaw wyników nie są zgodne z wartością. Metoda pobiera również informacje o ograniczeniach z zestawu wyników dla wszystkich dodanych kolumn. Z wyjątkiem przypadku ograniczenia klucza podstawowego te informacje ograniczenia są używane tylko wtedy, gdy bieżący DataTable nie zawiera żadnych kolumn na początku operacji ładowania.
Schematy są zgodne, ale załadowany schemat zestawu wyników zawiera mniej kolumn niż DataTable. Jeśli brak kolumny ma zdefiniowaną wartość domyślną lub typ danych kolumny ma wartość null, Load metoda umożliwia dodanie wierszy, zastąpienie wartości domyślnej lub null brakującej kolumny. Jeśli nie można użyć wartości domyślnej lub wartości null, Load metoda zgłasza wyjątek. Jeśli nie podano określonej wartości domyślnej, Load metoda używa wartości null jako dorozumianej wartości domyślnej.

Przed rozważeniem zachowania Load metody w zakresie operacji danych należy wziąć pod uwagę, że każdy wiersz w obrębie elementu DataTable zachowuje zarówno bieżącą wartość, jak i oryginalną wartość dla każdej kolumny. Te wartości mogą być równoważne lub mogą być inne, jeśli dane w wierszu zostały zmienione od czasu wypełnienia elementu DataTable. Aby uzyskać więcej informacji, zobacz Stany wierszy i wersje wierszy .

W tym wywołaniu metody określony LoadOption parametr wpływa na przetwarzanie danych przychodzących. Jak metoda Load powinna obsługiwać ładowanie wierszy, które mają ten sam klucz podstawowy co istniejące wiersze? Czy należy zmodyfikować bieżące wartości, oryginalne wartości lub oba te wartości? Te problemy i nie tylko są kontrolowane przez loadOption parametr .

Jeśli istniejący wiersz i wiersz przychodzący zawierają odpowiednie wartości klucza podstawowego, wiersz jest przetwarzany przy użyciu bieżącej wartości stanu wiersza, w przeciwnym razie jest traktowany jako nowy wiersz.

Jeśli chodzi o operacje zdarzenia, RowChanging zdarzenie występuje przed zmianą każdego wiersza, a RowChanged zdarzenie występuje po zmianie każdego wiersza. W każdym przypadku Action właściwość wystąpienia przekazanego DataRowChangeEventArgs do programu obsługi zdarzeń zawiera informacje o określonej akcji skojarzonej ze zdarzeniem. Ta wartość akcji różni się w zależności od stanu wiersza przed operacją ładowania. W każdym przypadku występują oba zdarzenia, a akcja jest taka sama dla każdego z nich. Akcja może być stosowana do bieżącej lub oryginalnej wersji każdego wiersza lub obu tych elementów w zależności od bieżącego stanu wiersza.

W poniższej tabeli przedstawiono zachowanie metody Load po wywołaniu z każdą z LoadOption wartości, a także pokazano, jak wartości wchodzą w interakcję ze stanem wiersza dla ładowanego wiersza. Ostatni wiersz (oznaczony etykietą "(Nie ma)") opisuje zachowanie dla wierszy przychodzących, które nie pasują do żadnego istniejącego wiersza. Każda komórka w tej tabeli opisuje bieżącą i oryginalną wartość pola w wierszu wraz z DataRowState wartością dla wartości po zakończeniu Load metody.

Istniejąca dataRowState Upsert Overwritechanges PreserveChanges (zachowanie domyślne)
Dodane Current = <Przychodzące>

Oryginalny = -<Niedostępny>

State = Added (Stan = Dodano) <>

RowAction = Zmiana
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Oryginał = <przychodzące>

State = Modified (Stan = <Zmodyfikowane)>

RowAction = ChangeOriginal
Zmodyfikowano Current = <Przychodzące>

Oryginalny = <istniejący>

State = Modified (Stan = <Zmodyfikowane)>

RowAction = Zmiana
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Existing>

Oryginał = <przychodzące>

State = Modified (Stan = <Zmodyfikowane)>

RowAction =ChangeOriginal
eletowane (Ładowanie nie ma wpływu na usunięte wiersze)

Current = ---

Oryginalny = <istniejący>

Stan = <Usunięto>

(Nowy wiersz jest dodawany z następującymi cechami)

Current = <Przychodzące>

Oryginalny = <niedostępny>

State = Added (Stan = Dodano) <>

RowAction = Dodaj
Cofnij usuwanie i

Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Niedostępne>

Oryginał = <przychodzące>

Stan = <Usunięto>

RowAction = ChangeOriginal
Niezmienione Current = <Przychodzące>

Oryginalny = <istniejący>

Jeśli nowa wartość jest taka sama jak istniejąca wartość, wówczas

State = <Bez zmian>

RowAction = Nic

Innego

State = Modified (Stan = <Zmodyfikowane)>

RowAction = Zmiana
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Brak obecności) Current = <Przychodzące>

Oryginalny = <niedostępny>

State = Added (Stan = Dodano) <>

RowAction = Dodaj
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal
Current = <Przychodzące>

Oryginał = <przychodzące>

State = <Bez zmian>

RowAction = ChangeCurrentAndOriginal

Wartości w obiekcie DataColumn mogą być ograniczone za pomocą właściwości, takich jak ReadOnly i AutoIncrement. Metoda Load obsługuje takie kolumny w sposób zgodny z zachowaniem zdefiniowanym przez właściwości kolumny. Ograniczenie tylko do odczytu w obiekcie DataColumn ma zastosowanie tylko w przypadku zmian występujących w pamięci. W Load razie potrzeby metoda zastępuje wartości kolumn tylko do odczytu.

Jeśli podczas wywoływania Load metody określisz opcje OverwriteChanges lub PreserveChanges, zakłada się, że dane przychodzące pochodzą z podstawowego DataTableźródła danych, a tabela DataTable śledzi zmiany i może propagować zmiany z powrotem do źródła danych. Jeśli wybierzesz opcję Upsert, zakłada się, że dane pochodzą z jednego z pomocniczych źródeł danych, takich jak dane dostarczone przez składnik warstwy środkowej, być może zmienione przez użytkownika. W takim przypadku założeniem jest to, że celem jest agregowanie danych z co najmniej jednego źródła danych w obiekcie DataTable, a następnie propagowanie danych z powrotem do podstawowego źródła danych. Parametr LoadOption służy do określania określonej wersji wiersza, który ma być używany do porównania klucza podstawowego. Poniższa tabela zawiera szczegółowe informacje.

Opcja ładowania Wersja DataRow używana do porównania klucza podstawowego
OverwriteChanges Oryginalna wersja, jeśli istnieje, w przeciwnym razie bieżąca wersja
PreserveChanges Oryginalna wersja, jeśli istnieje, w przeciwnym razie bieżąca wersja
Upsert Bieżąca wersja, jeśli istnieje, w przeciwnym razie oryginalna wersja

Parametr errorHandler jest delegatem FillErrorEventHandler , który odwołuje się do procedury wywoływanej w przypadku wystąpienia błędu podczas ładowania danych. Parametr FillErrorEventArgs przekazany do procedury zawiera właściwości, które umożliwiają pobieranie informacji o błędzie, który wystąpił, bieżący wiersz danych i DataTable wypełniane. Korzystanie z tego mechanizmu delegata, a nie prostszego bloku try/catch, umożliwia określenie błędu, obsługę sytuacji i kontynuowanie przetwarzania, jeśli chcesz. Parametr FillErrorEventArgs dostarcza Continue właściwość: ustaw tę właściwość, aby wskazać true , że obsłużono błąd i chcesz kontynuować przetwarzanie. Ustaw właściwość na wartość false , aby wskazać, że chcesz zatrzymać przetwarzanie. Należy pamiętać, że ustawienie właściwości powoduje false , że kod, który wyzwolił problem, zgłasza wyjątek.

Zobacz też

Dotyczy