DataTable.Load Metode

Definisi

DataTable Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader. DataTable Jika sudah berisi baris, data masuk dari sumber data digabungkan dengan baris yang sudah ada.

Overload

Load(IDataReader)

DataTable Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader. DataTable Jika sudah berisi baris, data masuk dari sumber data digabungkan dengan baris yang sudah ada.

Load(IDataReader, LoadOption)

DataTable Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader. DataTable Jika sudah berisi baris, data masuk dari sumber data digabungkan dengan baris yang ada sesuai dengan nilai loadOption parameter.

Load(IDataReader, LoadOption, FillErrorEventHandler)

DataTable Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader menggunakan delegasi penanganan kesalahan.

Contoh

Contoh berikut menunjukkan beberapa masalah yang terlibat dengan memanggil Load metode . Pertama, contoh berfokus pada masalah skema, termasuk menyimpulkan IDataReaderskema dari skema yang dimuat, lalu menangani skema yang tidak kompatibel, dan skema dengan kolom yang hilang atau tambahan. Contohnya kemudian berfokus pada masalah data, termasuk menangani berbagai opsi pemuatan.

Catatan

Contoh ini menunjukkan cara menggunakan salah satu versi yang kelebihan beban .Load Untuk contoh lain yang mungkin tersedia, lihat topik kelebihan beban individual.

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

Keterangan

Metode Load ini dapat digunakan dalam beberapa skenario umum, semuanya berpusat di sekitar mendapatkan data dari sumber data tertentu dan menambahkannya ke kontainer data saat ini (dalam hal ini, a DataTable). Skenario ini menjelaskan penggunaan standar untuk DataTable, yang menjelaskan perilaku pembaruan dan penggabungannya.

DataTable Sinkronisasi atau pembaruan dengan satu sumber data utama. Trek DataTable berubah, memungkinkan sinkronisasi dengan sumber data utama. Selain itu, DataTable dapat menerima data inkremental dari satu atau beberapa sumber data sekunder. DataTable tidak bertanggung jawab untuk melacak perubahan untuk memungkinkan sinkronisasi dengan sumber data sekunder.

Mengingat kedua sumber data hipotetis ini, pengguna kemungkinan memerlukan salah satu perilaku berikut:

  • Menginisialisasi DataTable dari sumber data utama. Dalam skenario ini, pengguna ingin menginisialisasi kosong DataTable dengan nilai dari sumber data utama. Kemudian pengguna berniat untuk menyebarluaskan perubahan kembali ke sumber data utama.

  • Mempertahankan perubahan dan menyinkronkan kembali dari sumber data utama. Dalam skenario ini, pengguna ingin mengambil DataTable yang diisi dalam skenario sebelumnya dan melakukan sinkronisasi inkremental dengan sumber data utama, mempertahankan modifikasi yang dibuat di DataTable.

  • Umpan data inkremental dari sumber data sekunder. Dalam skenario ini, pengguna ingin menggabungkan perubahan dari satu atau beberapa sumber data sekunder, dan menyebarluaskan perubahan tersebut kembali ke sumber data utama.

Metode ini Load memungkinkan semua skenario ini. Semua kecuali salah satu kelebihan beban untuk metode ini memungkinkan Anda menentukan parameter opsi beban, yang menunjukkan bagaimana baris sudah dalam DataTable gabungan dengan baris yang dimuat. (Kelebihan beban yang tidak memungkinkan Anda menentukan perilaku menggunakan opsi beban default.) Tabel berikut ini menjelaskan tiga opsi beban yang disediakan oleh LoadOption enumerasi. Dalam setiap kasus, deskripsi menunjukkan perilaku ketika kunci utama baris dalam data masuk cocok dengan kunci utama baris yang ada.

Opsi Muat Deskripsi
PreserveChanges (default) Updates versi asli baris dengan nilai baris masuk.
OverwriteChanges Updates versi baris saat ini dan asli dengan nilai baris masuk.
Upsert Updates versi baris saat ini dengan nilai baris masuk.

Secara umum, PreserveChanges opsi dan OverwriteChanges ditujukan untuk skenario di mana pengguna perlu menyinkronkan DataSet dan perubahannya dengan sumber data utama. Opsi ini Upsert memfasilitasi agregasi perubahan dari satu atau beberapa sumber data sekunder.

Load(IDataReader)

Sumber:
DataTable.cs
Sumber:
DataTable.cs
Sumber:
DataTable.cs

DataTable Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader. DataTable Jika sudah berisi baris, data masuk dari sumber data digabungkan dengan baris yang sudah ada.

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)

Parameter

reader
IDataReader

Yang IDataReader menyediakan tataan hasil.

Contoh

Contoh berikut menunjukkan beberapa masalah yang terlibat dengan memanggil Load metode . Pertama, contoh berfokus pada masalah skema, termasuk menyimpulkan IDataReaderskema dari skema yang dimuat, lalu menangani skema yang tidak kompatibel, dan skema dengan kolom yang hilang atau tambahan. Contoh kemudian memanggil Load metode , menampilkan data baik sebelum dan sesudah operasi pemuatan.

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

Keterangan

Metode ini Load mengonsumsi tataan hasil pertama dari yang dimuat IDataReader, dan setelah berhasil diselesaikan, mengatur posisi pembaca ke tataan hasil berikutnya, jika ada. Saat mengonversi data, Load metode ini menggunakan aturan konversi yang sama dengan DbDataAdapter.Fill metode .

Metode Load harus mempertimbangkan tiga masalah tertentu saat memuat data dari IDataReader instans: skema, data, dan operasi peristiwa. Saat bekerja dengan skema, Load metode mungkin mengalami kondisi seperti yang dijelaskan dalam tabel berikut. Operasi skema berlangsung untuk semua tataan hasil yang diimpor, bahkan yang tidak berisi data.

Kondisi Aktivitas
Tidak DataTable memiliki skema. Metode menyimpulkan Load skema berdasarkan hasil yang ditetapkan dari yang diimpor IDataReader.
DataTable memiliki skema, tetapi tidak kompatibel dengan skema yang dimuat. Metode ini Load memberikan pengecualian yang sesuai dengan kesalahan tertentu yang terjadi saat mencoba memuat data ke dalam skema yang tidak kompatibel.
Skema kompatibel, tetapi skema kumpulan hasil yang dimuat berisi kolom yang tidak ada di DataTable. Metode menambahkan Load kolom tambahan ke DataTableskema . Metode ini memberikan pengecualian jika kolom terkait di dan tataan hasil yang dimuat DataTable tidak kompatibel dengan nilai. Metode ini juga mengambil informasi batasan dari hasil yang ditetapkan untuk semua kolom yang ditambahkan. Kecuali untuk kasus batasan Kunci Primer, informasi batasan ini hanya digunakan jika saat ini DataTable tidak berisi kolom apa pun di awal operasi pemuatan.
Skema kompatibel, tetapi skema kumpulan hasil yang dimuat berisi lebih sedikit kolom daripada DataTable. Jika kolom yang hilang memiliki nilai default yang ditentukan atau jenis data kolom dapat diubah ke null, Load metode ini memungkinkan baris ditambahkan, menggantikan default atau null nilai untuk kolom yang hilang. Jika tidak ada nilai default atau null dapat digunakan, maka Load metode melemparkan pengecualian. Jika tidak ada nilai default tertentu yang disediakan, Load metode menggunakan null nilai sebagai nilai default tersirat.

Sebelum mempertimbangkan perilaku Load metode dalam hal operasi data, pertimbangkan bahwa setiap baris dalam DataTable mempertahankan nilai saat ini dan nilai asli untuk setiap kolom. Nilai-nilai ini mungkin setara, atau mungkin berbeda jika data dalam baris telah diubah sejak mengisi DataTable. Untuk informasi selengkapnya, lihat Status Baris dan Versi Baris.

Versi Load metode ini mencoba mempertahankan nilai saat ini di setiap baris, membiarkan nilai asli tetap utuh. (Jika Anda ingin kontrol yang lebih baik atas perilaku data masuk, lihat DataTable.Load.) Jika baris yang sudah ada dan baris masuk berisi nilai kunci primer yang sesuai, baris diproses menggunakan nilai status baris saat ini, jika tidak, baris tersebut diperlakukan sebagai baris baru.

Dalam hal operasi peristiwa, RowChanging peristiwa terjadi sebelum setiap baris diubah, dan RowChanged peristiwa terjadi setelah setiap baris diubah. Dalam setiap kasus, Action properti instans yang DataRowChangeEventArgs diteruskan ke penanganan aktivitas berisi informasi tentang tindakan tertentu yang terkait dengan peristiwa. Nilai tindakan ini tergantung pada status baris sebelum operasi pemuatan. Dalam setiap kasus, kedua peristiwa terjadi, dan tindakannya sama untuk masing-masing peristiwa. Tindakan dapat diterapkan ke versi saat ini atau asli dari setiap baris, atau keduanya, tergantung pada status baris saat ini.

Tabel berikut menampilkan perilaku untuk metode .Load Baris akhir (berlabel "(Tidak ada)") menjelaskan perilaku untuk baris masuk yang tidak cocok dengan baris yang ada. Setiap sel dalam tabel ini menjelaskan nilai saat ini dan asli untuk bidang dalam baris, bersama dengan DataRowState untuk nilai setelah Load metode selesai. Dalam hal ini, metode ini tidak memungkinkan Anda untuk menunjukkan opsi beban, dan menggunakan default, PreserveChanges.

DataRowState yang Ada Nilai setelah Load metode, dan tindakan peristiwa
Ditambahkan Saat Ini = <Yang Ada>

Asli = <Masuk>

Status = <Diubah>

RowAction = ChangeOriginal
Dimodifikasi Saat Ini = <Yang Ada>

Asli = <Masuk>

Status = <Diubah>

RowAction = ChangeOriginal
Dihapus Saat ini = <Tidak tersedia>

Asli = <Masuk>

Status = <Dihapus>

RowAction = ChangeOriginal
Tidak diubah Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
(Tidak ada) Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal

Nilai dalam dapat dibatasi DataColumn melalui penggunaan properti seperti ReadOnly dan AutoIncrement. Metode Load ini menangani kolom tersebut dengan cara yang konsisten dengan perilaku yang ditentukan oleh properti kolom. Batasan baca saja pada DataColumn hanya berlaku untuk perubahan yang terjadi dalam memori. Metode Load ini menimpa nilai kolom baca-saja, jika diperlukan.

Untuk menentukan versi bidang kunci primer mana yang akan digunakan untuk membandingkan baris saat ini dengan baris masuk, Load metode menggunakan versi asli dari nilai kunci primer dalam baris, jika ada. Jika tidak, Load metode menggunakan versi bidang kunci primer saat ini.

Lihat juga

Berlaku untuk

Load(IDataReader, LoadOption)

Sumber:
DataTable.cs
Sumber:
DataTable.cs
Sumber:
DataTable.cs

DataTable Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader. DataTable Jika sudah berisi baris, data masuk dari sumber data digabungkan dengan baris yang ada sesuai dengan nilai loadOption parameter.

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

Parameter

reader
IDataReader

Yang IDataReader menyediakan satu atau beberapa tataan hasil.

loadOption
LoadOption

Nilai dari LoadOption enumerasi yang menunjukkan bagaimana baris yang sudah ada di digabungkan DataTable dengan baris masuk yang memiliki kunci primer yang sama.

Contoh

Contoh berikut menunjukkan beberapa masalah yang terlibat dengan memanggil Load metode . Pertama, contoh berfokus pada masalah skema, termasuk menyimpulkan IDataReaderskema dari skema yang dimuat, lalu menangani skema yang tidak kompatibel, dan skema dengan kolom yang hilang atau tambahan. Contohnya kemudian berfokus pada masalah data, termasuk menangani berbagai opsi pemuatan.

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

Keterangan

Metode ini Load mengonsumsi tataan hasil pertama dari yang dimuat IDataReader, dan setelah berhasil diselesaikan, mengatur posisi pembaca ke tataan hasil berikutnya, jika ada. Saat mengonversi data, Load metode ini menggunakan aturan konversi yang sama dengan Fill metode .

Metode Load harus mempertimbangkan tiga masalah tertentu saat memuat data dari IDataReader instans: skema, data, dan operasi peristiwa. Saat bekerja dengan skema, Load metode mungkin mengalami kondisi seperti yang dijelaskan dalam tabel berikut. Operasi skema berlangsung untuk semua tataan hasil yang diimpor, bahkan yang tidak berisi data.

Kondisi Aktivitas
Tidak DataTable memiliki skema. Metode menyimpulkan Load skema berdasarkan hasil yang ditetapkan dari yang diimpor IDataReader.
DataTable memiliki skema, tetapi tidak kompatibel dengan skema yang dimuat. Metode ini Load memberikan pengecualian yang sesuai dengan kesalahan tertentu yang terjadi saat mencoba memuat data ke dalam skema yang tidak kompatibel.
Skema kompatibel, tetapi skema kumpulan hasil yang dimuat berisi kolom yang tidak ada di DataTable. Metode menambahkan Load kolom tambahan ke DataTableskema . Metode ini memberikan pengecualian jika kolom terkait di dan tataan hasil yang dimuat DataTable tidak kompatibel dengan nilai. Metode ini juga mengambil informasi batasan dari hasil yang ditetapkan untuk semua kolom yang ditambahkan. Kecuali untuk kasus batasan Kunci Primer, informasi batasan ini hanya digunakan jika saat ini DataTable tidak berisi kolom apa pun di awal operasi pemuatan.
Skema kompatibel, tetapi skema kumpulan hasil yang dimuat berisi lebih sedikit kolom daripada DataTable. Jika kolom yang hilang memiliki nilai default yang ditentukan atau jenis data kolom dapat diubah ke null, metode ini Load memungkinkan baris ditambahkan, mengganti nilai default atau null untuk kolom yang hilang. Jika tidak ada nilai default atau null yang dapat digunakan, maka Load metode melemparkan pengecualian. Jika tidak ada nilai default tertentu yang disediakan, Load metode menggunakan nilai null sebagai nilai default tersirat.

Sebelum mempertimbangkan perilaku Load metode dalam hal operasi data, pertimbangkan bahwa setiap baris dalam DataTable mempertahankan nilai saat ini dan nilai asli untuk setiap kolom. Nilai-nilai ini mungkin setara, atau mungkin berbeda jika data dalam baris telah diubah sejak mengisi DataTable. Lihat Status Baris dan Versi Baris untuk informasi selengkapnya.

Dalam panggilan metode ini, parameter yang ditentukan LoadOption memengaruhi pemrosesan data masuk. Bagaimana metode Muat harus menangani pemuatan baris yang memiliki kunci primer yang sama dengan baris yang ada? Haruskah mengubah nilai saat ini, nilai asli, atau keduanya? Masalah ini, dan banyak lagi, dikendalikan oleh loadOption parameter .

Jika baris yang sudah ada dan baris masuk berisi nilai kunci primer yang sesuai, baris diproses menggunakan nilai status baris saat ini, jika tidak, baris tersebut diperlakukan sebagai baris baru.

Dalam hal operasi peristiwa, RowChanging peristiwa terjadi sebelum setiap baris diubah, dan RowChanged peristiwa terjadi setelah setiap baris diubah. Dalam setiap kasus, Action properti instans yang DataRowChangeEventArgs diteruskan ke penanganan aktivitas berisi informasi tentang tindakan tertentu yang terkait dengan peristiwa. Nilai tindakan ini bervariasi, tergantung pada status baris sebelum operasi pemuatan. Dalam setiap kasus, kedua peristiwa terjadi, dan tindakannya sama untuk masing-masing peristiwa. Tindakan dapat diterapkan ke versi saat ini atau asli dari setiap baris, atau keduanya, tergantung pada status baris saat ini.

Tabel berikut ini menampilkan perilaku untuk metode Muat saat dipanggil dengan setiap LoadOption nilai, dan juga memperlihatkan bagaimana nilai berinteraksi dengan status baris untuk baris yang dimuat. Baris akhir (berlabel "(Tidak ada)") menjelaskan perilaku untuk baris masuk yang tidak cocok dengan baris yang ada. Setiap sel dalam tabel ini menjelaskan nilai saat ini dan asli untuk bidang dalam baris, bersama dengan DataRowState untuk nilai setelah Load metode selesai.

DataRowState yang Ada Upsert OverwriteChanges PreserveChanges (Perilaku default)
Ditambahkan Saat Ini = <Masuk>

Asli = -<Tidak tersedia>

Status = <Ditambahkan>

RowAction = Ubah
Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat Ini = <Yang Ada>

Asli = <Masuk>

Status = <Diubah>

RowAction = ChangeOriginal
Dimodifikasi Saat Ini = <Masuk>

Asli = <Yang Ada>

Status = <Diubah>

RowAction = Ubah
Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat Ini = <Yang Ada>

Asli = <Masuk>

Status = <Diubah>

RowAction =ChangeOriginal
Dihapus (Muat tidak memengaruhi baris yang dihapus)

Saat ini = ---

Asli = <Yang Ada>

Status = <Dihapus>

(Baris baru ditambahkan dengan karakteristik berikut)

Saat Ini = <Masuk>

Asli = <Tidak tersedia>

Status = <Ditambahkan>

RowAction = Tambahkan
Batalkan penghapusan dan

Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat ini = <Tidak tersedia>

Asli = <Masuk>

Status = <Dihapus>

RowAction = ChangeOriginal
Tidak diubah Saat Ini = <Masuk>

Asli = <Yang Ada>

Jika nilai baru sama dengan nilai yang ada, maka

Status = <Tidak Berubah>

RowAction = Tidak ada

Lain

Status = <Diubah>

RowAction = Ubah
Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Tidak ada) Saat Ini = <Masuk>

Asli = <Tidak tersedia>

Status = <Ditambahkan>

RowAction = Tambahkan
Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal

Nilai dalam dapat dibatasi DataColumn melalui penggunaan properti seperti ReadOnly dan AutoIncrement. Metode Load ini menangani kolom tersebut dengan cara yang konsisten dengan perilaku yang ditentukan oleh properti kolom. Batasan baca saja pada DataColumn hanya berlaku untuk perubahan yang terjadi dalam memori. Metode Load ini menimpa nilai kolom baca-saja, jika diperlukan.

Jika Anda menentukan opsi OverwriteChanges atau PreserveChanges saat memanggil Load metode, maka asumsi dibuat bahwa data masuk berasal dari DataTablesumber data utama, dan DataTable melacak perubahan dan dapat menyebarkan perubahan kembali ke sumber data. Jika Anda memilih opsi Upsert, diasumsikan bahwa data berasal dari salah satu sumber data sekunder, seperti data yang disediakan oleh komponen tingkat menengah, mungkin diubah oleh pengguna. Dalam hal ini, asumsinya adalah bahwa niatnya adalah untuk mengagregasi data dari satu atau beberapa sumber data di DataTable, dan kemudian mungkin menyebarluaskan data kembali ke sumber data utama. Parameter LoadOption digunakan untuk menentukan versi tertentu dari baris yang akan digunakan untuk perbandingan kunci primer. Tabel di bawah ini menyediakan detailnya.

Opsi muat Versi DataRow yang digunakan untuk perbandingan kunci primer
OverwriteChanges Versi asli, jika ada, jika tidak Versi saat ini
PreserveChanges Versi asli, jika ada, jika tidak Versi saat ini
Upsert Versi saat ini, jika ada, jika tidak Versi asli

Lihat juga

Berlaku untuk

Load(IDataReader, LoadOption, FillErrorEventHandler)

Sumber:
DataTable.cs
Sumber:
DataTable.cs
Sumber:
DataTable.cs

DataTable Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader menggunakan delegasi penanganan kesalahan.

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)

Parameter

reader
IDataReader

IDataReader yang menyediakan tataan hasil.

loadOption
LoadOption

Nilai dari LoadOption enumerasi yang menunjukkan bagaimana baris yang sudah ada di digabungkan DataTable dengan baris masuk yang memiliki kunci primer yang sama.

errorHandler
FillErrorEventHandler

FillErrorEventHandler Delegasi untuk memanggil saat terjadi kesalahan saat memuat data.

Contoh

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

Keterangan

Metode ini Load mengonsumsi tataan hasil pertama dari yang dimuat IDataReader, dan setelah berhasil diselesaikan, mengatur posisi pembaca ke tataan hasil berikutnya, jika ada. Saat mengonversi data, Load metode ini menggunakan aturan konversi yang sama dengan DbDataAdapter.Fill metode .

Metode Load harus mempertimbangkan tiga masalah tertentu saat memuat data dari IDataReader instans: skema, data, dan operasi peristiwa. Saat bekerja dengan skema, Load metode mungkin mengalami kondisi seperti yang dijelaskan dalam tabel berikut. Operasi skema berlangsung untuk semua tataan hasil yang diimpor, bahkan yang tidak berisi data.

Kondisi Aktivitas
Tidak DataTable memiliki skema. Metode menyimpulkan Load skema berdasarkan hasil yang ditetapkan dari yang diimpor IDataReader.
DataTable memiliki skema, tetapi tidak kompatibel dengan skema yang dimuat. Metode ini Load memberikan pengecualian yang sesuai dengan kesalahan tertentu yang terjadi saat mencoba memuat data ke dalam skema yang tidak kompatibel.
Skema kompatibel, tetapi skema kumpulan hasil yang dimuat berisi kolom yang tidak ada di DataTable. Metode menambahkan Load kolom tambahan ke DataTableskema . Metode ini memberikan pengecualian jika kolom terkait di dan tataan hasil yang dimuat DataTable tidak kompatibel dengan nilai. Metode ini juga mengambil informasi batasan dari hasil yang ditetapkan untuk semua kolom yang ditambahkan. Kecuali untuk kasus batasan Kunci Primer, informasi batasan ini hanya digunakan jika saat ini DataTable tidak berisi kolom apa pun di awal operasi pemuatan.
Skema kompatibel, tetapi skema kumpulan hasil yang dimuat berisi lebih sedikit kolom daripada DataTable. Jika kolom yang hilang memiliki nilai default yang ditentukan atau jenis data kolom dapat diubah ke null, metode ini Load memungkinkan baris ditambahkan, mengganti nilai default atau null untuk kolom yang hilang. Jika tidak ada nilai default atau null yang dapat digunakan, maka Load metode melemparkan pengecualian. Jika tidak ada nilai default tertentu yang disediakan, Load metode menggunakan nilai null sebagai nilai default tersirat.

Sebelum mempertimbangkan perilaku Load metode dalam hal operasi data, pertimbangkan bahwa setiap baris dalam DataTable mempertahankan nilai saat ini dan nilai asli untuk setiap kolom. Nilai-nilai ini mungkin setara, atau mungkin berbeda jika data dalam baris telah diubah sejak mengisi DataTable. Lihat Status Baris dan Versi Baris untuk informasi selengkapnya.

Dalam panggilan metode ini, parameter yang ditentukan LoadOption memengaruhi pemrosesan data masuk. Bagaimana metode Muat harus menangani pemuatan baris yang memiliki kunci primer yang sama dengan baris yang ada? Haruskah mengubah nilai saat ini, nilai asli, atau keduanya? Masalah ini, dan banyak lagi, dikendalikan oleh loadOption parameter .

Jika baris yang sudah ada dan baris masuk berisi nilai kunci primer yang sesuai, baris diproses menggunakan nilai status baris saat ini, jika tidak, baris tersebut diperlakukan sebagai baris baru.

Dalam hal operasi peristiwa, RowChanging peristiwa terjadi sebelum setiap baris diubah, dan RowChanged peristiwa terjadi setelah setiap baris diubah. Dalam setiap kasus, Action properti instans yang DataRowChangeEventArgs diteruskan ke penanganan aktivitas berisi informasi tentang tindakan tertentu yang terkait dengan peristiwa. Nilai tindakan ini bervariasi, tergantung pada status baris sebelum operasi pemuatan. Dalam setiap kasus, kedua peristiwa terjadi, dan tindakannya sama untuk masing-masing peristiwa. Tindakan dapat diterapkan ke versi saat ini atau asli dari setiap baris, atau keduanya, tergantung pada status baris saat ini.

Tabel berikut ini menampilkan perilaku untuk metode Muat saat dipanggil dengan setiap LoadOption nilai, dan juga memperlihatkan bagaimana nilai berinteraksi dengan status baris untuk baris yang dimuat. Baris akhir (berlabel "(Tidak ada)") menjelaskan perilaku untuk baris masuk yang tidak cocok dengan baris yang ada. Setiap sel dalam tabel ini menjelaskan nilai saat ini dan asli untuk bidang dalam baris, bersama dengan DataRowState untuk nilai setelah Load metode selesai.

DataRowState yang Ada Upsert OverwriteChanges PreserveChanges (Perilaku default)
Ditambahkan Saat Ini = <Masuk>

Asli = -<Tidak tersedia>

Status = <Ditambahkan>

RowAction = Ubah
Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat Ini = <Yang Ada>

Asli = <Masuk>

Status = <Diubah>

RowAction = ChangeOriginal
Dimodifikasi Saat Ini = <Masuk>

Asli = <Yang Ada>

Status = <Diubah>

RowAction = Ubah
Saat Ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat Ini = <Yang Ada>

Asli = <Masuk>

Status = <Dimodifikasi>

RowAction =ChangeOriginal
dihapus (Muat tidak mempengaruhi baris yang dihapus)

Saat ini = ---

Asli = <Yang Ada>

Status = <Dihapus>

(Baris baru ditambahkan dengan karakteristik berikut)

Saat ini = <Masuk>

Asli = <Tidak tersedia>

Status = <Ditambahkan>

RowAction = Tambahkan
Batalkan penghapusan dan

Saat ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat ini = <Tidak tersedia>

Asli = <Masuk>

Status = <Dihapus>

RowAction = ChangeOriginal
Tidak diubah Saat ini = <Masuk>

Asli = <Yang Ada>

Jika nilai baru sama dengan nilai yang ada maka

Status = <Tidak Berubah>

RowAction = Tidak ada

Lain

Status = <Dimodifikasi>

RowAction = Ubah
Saat ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Tidak ada) Saat ini = <Masuk>

Asli = <Tidak tersedia>

Status = <Ditambahkan>

RowAction = Tambahkan
Saat ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal
Saat ini = <Masuk>

Asli = <Masuk>

Status = <Tidak Berubah>

RowAction = ChangeCurrentAndOriginal

Nilai dalam dapat dibatasi DataColumn melalui penggunaan properti seperti ReadOnly dan AutoIncrement. Metode Load menangani kolom tersebut dengan cara yang konsisten dengan perilaku yang ditentukan oleh properti kolom. Batasan baca saja pada hanya DataColumn berlaku untuk perubahan yang terjadi dalam memori. Metode Load ini menimpa nilai kolom baca-saja, jika diperlukan.

Jika Anda menentukan opsi OverwriteChanges atau PreserveChanges saat memanggil Load metode, maka asumsi dibuat bahwa data masuk berasal dari DataTablesumber data utama, dan DataTable melacak perubahan dan dapat menyebarluaskan perubahan kembali ke sumber data. Jika Anda memilih opsi Upsert, diasumsikan bahwa data berasal dari salah satu sumber data sekunder, seperti data yang disediakan oleh komponen tingkat menengah, mungkin diubah oleh pengguna. Dalam hal ini, asumsinya adalah bahwa niatnya adalah untuk menggabungkan data dari satu atau beberapa sumber data di DataTable, dan kemudian mungkin menyebarluaskan data kembali ke sumber data utama. Parameter LoadOption digunakan untuk menentukan versi tertentu dari baris yang akan digunakan untuk perbandingan kunci primer. Tabel di bawah ini menyediakan detailnya.

Opsi muat Versi DataRow yang digunakan untuk perbandingan kunci primer
OverwriteChanges Versi asli, jika ada, jika tidak Versi saat ini
PreserveChanges Versi asli, jika ada, jika tidak Versi saat ini
Upsert Versi saat ini, jika ada, jika tidak Versi asli

Parameter errorHandler adalah FillErrorEventHandler delegasi yang mengacu pada prosedur yang dipanggil ketika kesalahan terjadi saat memuat data. Parameter FillErrorEventArgs yang diteruskan ke prosedur menyediakan properti yang memungkinkan Anda mengambil informasi tentang kesalahan yang terjadi, baris data saat ini, dan yang DataTable sedang diisi. Menggunakan mekanisme delegasi ini, daripada blok coba/tangkap yang lebih sederhana, memungkinkan Anda menentukan kesalahan, menangani situasi, dan melanjutkan pemrosesan jika Anda mau. Parameter FillErrorEventArgs menyediakan Continue properti: atur properti ini ke true untuk menunjukkan bahwa Anda telah menangani kesalahan dan ingin melanjutkan pemrosesan. Atur properti ke false untuk menunjukkan bahwa Anda ingin menghentikan pemrosesan. Ketahuilah bahwa mengatur properti untuk false menyebabkan kode yang memicu masalah untuk melemparkan pengecualian.

Lihat juga

Berlaku untuk