DataSet.Load Metode

Definisi

DataSet Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader.

Overload

Load(IDataReader, LoadOption, DataTable[])

DataSet Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader, menggunakan array DataTable instans untuk menyediakan informasi skema dan namespace.

Load(IDataReader, LoadOption, String[])

DataSet Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader, menggunakan array string untuk menyediakan nama untuk tabel dalam DataSet.

Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[])

DataSet Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader, menggunakan array DataTable instans untuk menyediakan informasi skema dan namespace.

Keterangan

Metode ini Load menyediakan teknik untuk mengisi satu DataTable dengan data, yang diambil dari IDataReader instans. Metode ini menyediakan fungsionalitas yang sama, tetapi memungkinkan Anda memuat beberapa tataan hasil dari IDataReader ke dalam beberapa tabel dalam DataSet.

DataSet Jika sudah berisi baris, data masuk dari sumber data digabungkan dengan baris yang sudah ada.

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 DataSet). Skenario ini menjelaskan penggunaan standar untuk DataSet, yang menjelaskan perilaku pembaruan dan penggabungannya.

DataSet Sinkronisasi atau pembaruan dengan satu sumber data utama. Trek DataSet berubah, memungkinkan sinkronisasi dengan sumber data utama. Selain itu, DataSet dapat menerima data inkremental dari satu atau beberapa sumber data sekunder. DataSet 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 DataSet dari sumber data utama. Dalam skenario ini, pengguna ingin menginisialisasi kosong DataSet dengan nilai dari sumber data utama. Satu atau beberapa konten DataTable dimodifikasi. 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 DataSet yang diisi dalam skenario sebelumnya dan melakukan sinkronisasi inkremental dengan sumber data utama, mempertahankan modifikasi yang dibuat di DataSet.

  • 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. Metode ini memungkinkan Anda menentukan parameter opsi beban, yang menunjukkan bagaimana baris sudah dalam DataTable gabungan dengan baris yang dimuat. 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, LoadOption, DataTable[])

Sumber:
DataSet.cs
Sumber:
DataSet.cs
Sumber:
DataSet.cs

DataSet Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader, menggunakan array DataTable instans untuk menyediakan informasi skema dan namespace.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, ... cli::array <System::Data::DataTable ^> ^ tables);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, params System.Data.DataTable[] tables);
member this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.DataTable[] -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption, ParamArray tables As DataTable())

Parameter

reader
IDataReader

Yang IDataReader menyediakan satu atau beberapa tataan hasil.

loadOption
LoadOption

Nilai dari LoadOption enumerasi yang menunjukkan bagaimana baris yang sudah ada dalam instans DataSet dalam DataTable akan dikombinasikan dengan baris masuk yang memiliki kunci primer yang sama.

tables
DataTable[]

Array DataTable instans, dari mana Load(IDataReader, LoadOption, DataTable[]) metode mengambil informasi nama dan namespace. Masing-masing tabel ini harus menjadi anggota yang DataTableCollection terkandung oleh ini DataSet.

Contoh

Contoh berikut membuat baru DataSet, menambahkan dua DataTable instans ke DataSet, lalu mengisi DataSet menggunakan Load metode , mengambil data dari DataTableReader yang berisi dua tataan hasil. Terakhir, contoh menampilkan konten tabel di jendela konsol.

static void Main()
{
    DataSet dataSet = new DataSet();

    DataTable customerTable = new DataTable();
    DataTable productTable = new DataTable();

    // This information is cosmetic, only.
    customerTable.TableName = "Customers";
    productTable.TableName = "Products";

    // Add the tables to the DataSet:
    dataSet.Tables.Add(customerTable);
    dataSet.Tables.Add(productTable);

    // Load the data into the existing DataSet.
    DataTableReader reader = GetReader();
    dataSet.Load(reader, LoadOption.OverwriteChanges,
        customerTable, productTable);

    // Print out the contents of each table:
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static DataTable GetCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();
    table.TableName = "Customers";

    // 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 GetProducts()
{
    // Create sample Products table.
    DataTable table = new DataTable();
    table.TableName = "Products";

    // 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, "Wireless Network Card" });
    table.Rows.Add(new object[] { 1, "Hard Drive" });
    table.Rows.Add(new object[] { 2, "Monitor" });
    table.Rows.Add(new object[] { 3, "CPU" });
    table.AcceptChanges();
    return table;
}

private static void PrintColumns(DataTable table)
{
    Console.WriteLine();
    Console.WriteLine(table.TableName);
    Console.WriteLine("=========================");
    // Loop through all the rows in the table:
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i] + " ");
        }
        Console.WriteLine();
    }
}

private static DataTableReader GetReader()
{
    // Return a DataTableReader containing multiple
    // result sets, just for the sake of this demo.
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());
    return dataSet.CreateDataReader();
}
Sub Main()
    Dim dataSet As New DataSet

    Dim customerTable As New DataTable
    Dim productTable As New DataTable

    ' This information is cosmetic, only.
    customerTable.TableName = "Customers"
    productTable.TableName = "Products"

    ' Add the tables to the DataSet:
    dataSet.Tables.Add(customerTable)
    dataSet.Tables.Add(productTable)

    ' Load the data into the existing DataSet. 
    Dim reader As DataTableReader = GetReader()
    dataSet.Load(reader, LoadOption.OverwriteChanges, _
        customerTable, productTable)

    ' Print out the contents of each table:
    For Each table As DataTable In dataSet.Tables
        PrintColumns(table)
    Next

    Console.WriteLine("Press any key to continue.")
    Console.ReadKey()
End Sub

Private Function GetCustomers() As DataTable
    ' Create sample Customers table.
    Dim table As New DataTable
    table.TableName = "Customers"

    ' 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 GetProducts() As DataTable
    ' Create sample Products table, in order
    ' to demonstrate the behavior of the DataTableReader.
    Dim table As New DataTable
    table.TableName = "Products"

    ' 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, "Wireless Network Card"})
    table.Rows.Add(New Object() {1, "Hard Drive"})
    table.Rows.Add(New Object() {2, "Monitor"})
    table.Rows.Add(New Object() {3, "CPU"})
    Return table
End Function

Private Function GetReader() As DataTableReader
    ' Return a DataTableReader containing multiple
    ' result sets, just for the sake of this demo.
    Dim dataSet As New DataSet
    dataSet.Tables.Add(GetCustomers())
    dataSet.Tables.Add(GetProducts())
    Return dataSet.CreateDataReader()
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

    Console.WriteLine()
    Console.WriteLine(table.TableName)
    Console.WriteLine("=========================")
    ' Loop through all the rows in the table.
    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 menyediakan teknik untuk mengisi satu DataTable dengan data, yang diambil dari IDataReader instans. Metode ini menyediakan fungsionalitas yang sama, tetapi memungkinkan Anda memuat beberapa tataan hasil dari IDataReader ke dalam beberapa tabel dalam DataSet.

Catatan

Operasi pemuatan akan gagal dengan InvalidOperationException jika salah satu kolom data sumber di yang masuk reader adalah kolom komputasi.

Parameter loadOption memungkinkan Anda menentukan bagaimana Anda ingin data yang diimpor berinteraksi dengan data yang ada, dan dapat menjadi salah satu nilai dari LoadOption enumerasi. Lihat dokumentasi untuk DataTableLoad metode untuk informasi selengkapnya tentang menggunakan parameter ini.

Parameter tables memungkinkan Anda menentukan array DataTable instans, yang menunjukkan urutan tabel yang sesuai dengan setiap kumpulan hasil yang dimuat dari pembaca. Metode ini Load mengisi setiap instans yang disediakan DataTable dengan data dari satu tataan hasil dari pembaca data sumber. Setelah setiap tataan Load hasil, metode berpindah ke hasil berikutnya yang diatur dalam pembaca, sampai tidak ada lagi tataan hasil.

Skema resolusi nama untuk metode ini sama dengan yang diikuti dengan Fill metode DbDataAdapter kelas .

Lihat juga

Berlaku untuk

Load(IDataReader, LoadOption, String[])

Sumber:
DataSet.cs
Sumber:
DataSet.cs
Sumber:
DataSet.cs

DataSet Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader, menggunakan array string untuk menyediakan nama untuk tabel dalam DataSet.

public:
 void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, ... cli::array <System::String ^> ^ tables);
public void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, params string[] tables);
member this.Load : System.Data.IDataReader * System.Data.LoadOption * string[] -> unit
Public Sub Load (reader As IDataReader, loadOption As LoadOption, ParamArray tables As String())

Parameter

reader
IDataReader

Yang IDataReader menyediakan satu atau beberapa tataan hasil.

loadOption
LoadOption

Nilai dari LoadOption enumerasi yang menunjukkan bagaimana baris yang sudah ada dalam instans DataSet dalam DataTable akan dikombinasikan dengan baris masuk yang memiliki kunci primer yang sama.

tables
String[]

Array string, dari mana Load metode mengambil informasi nama tabel.

Contoh

Contoh aplikasi Konsol berikut pertama-tama membuat tabel dan memuat data dari pembaca ke dalam DataSet, menggunakan Load metode . Contoh kemudian menambahkan tabel ke DataSet dan mencoba mengisi tabel dengan data dari DataTableReader. Dalam contoh ini, karena parameter yang diteruskan ke Load metode menunjukkan nama tabel yang tidak ada, Load metode membuat tabel baru agar sesuai dengan nama yang diteruskan sebagai parameter. Setelah data dimuat, contoh menampilkan konten semua tabelnya di jendela Konsol.

static void Main()
{
    DataSet dataSet = new DataSet();

    DataTableReader reader = GetReader();

    // The tables listed as parameters for the Load method
    // should be in the same order as the tables within the IDataReader.
    dataSet.Load(reader, LoadOption.Upsert, "Customers", "Products");
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

    // Now try the example with the DataSet
    // already filled with data:
    dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());

    // Retrieve a data reader containing changed data:
    reader = GetReader();

    // Load the data into the existing DataSet. Retrieve the order of the
    // the data in the reader from the
    // list of table names in the parameters. If you specify
    // a new table name here, the Load method will create
    // a corresponding new table.
    dataSet.Load(reader, LoadOption.Upsert,
        "NewCustomers", "Products");
    foreach (DataTable table in dataSet.Tables)
    {
        PrintColumns(table);
    }

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static DataTable GetCustomers()
{
    // Create sample Customers table.
    DataTable table = new DataTable();
    table.TableName = "Customers";

    // 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 GetProducts()
{
    // Create sample Products table.
    DataTable table = new DataTable();
    table.TableName = "Products";

    // 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, "Wireless Network Card" });
    table.Rows.Add(new object[] { 1, "Hard Drive" });
    table.Rows.Add(new object[] { 2, "Monitor" });
    table.Rows.Add(new object[] { 3, "CPU" });
    table.AcceptChanges();
    return table;
}

private static void PrintColumns(DataTable table)
{
    Console.WriteLine();
    Console.WriteLine(table.TableName);
    Console.WriteLine("=========================");
    // Loop through all the rows in the table:
    foreach (DataRow row in table.Rows)
    {
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Console.Write(row[i] + " ");
        }
        Console.WriteLine();
    }
}

private static DataTableReader GetReader()
{
    // Return a DataTableReader containing multiple
    // result sets, just for the sake of this demo.
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add(GetCustomers());
    dataSet.Tables.Add(GetProducts());
    return dataSet.CreateDataReader();
}
Sub Main()
  Dim dataSet As New DataSet
  Dim table As DataTable

  Dim reader As DataTableReader = GetReader()

  ' The tables listed as parameters for the Load method 
  ' should be in the same order as the tables within the IDataReader.
  dataSet.Load(reader, LoadOption.Upsert, "Customers", "Products")
  For Each table In dataSet.Tables
    PrintColumns(table)
  Next

  ' Now try the example with the DataSet
  ' already filled with data:
  dataSet = New DataSet
  dataSet.Tables.Add(GetCustomers())
  dataSet.Tables.Add(GetProducts())

  ' Retrieve a data reader containing changed data:
  reader = GetReader()

  ' Load the data into the existing DataSet. Retrieve the order of the
  ' the data in the reader from the
  ' list of table names in the parameters. If you specify
  ' a new table name here, the Load method will create
  ' a corresponding new table.
  dataSet.Load(reader, LoadOption.Upsert, "NewCustomers", "Products")
  For Each table In dataSet.Tables
    PrintColumns(table)
  Next

  Console.WriteLine("Press any key to continue.")
  Console.ReadKey()
End Sub

Private Function GetCustomers() As DataTable
  ' Create sample Customers table.
  Dim table As New DataTable
  table.TableName = "Customers"

  ' 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 GetProducts() As DataTable
  ' Create sample Products table, in order
  ' to demonstrate the behavior of the DataTableReader.
  Dim table As New DataTable
  table.TableName = "Products"

  ' 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, "Wireless Network Card"})
  table.Rows.Add(New Object() {1, "Hard Drive"})
  table.Rows.Add(New Object() {2, "Monitor"})
  table.Rows.Add(New Object() {3, "CPU"})
  Return table
End Function

Private Function GetReader() As DataTableReader
  ' Return a DataTableReader containing multiple
  ' result sets, just for the sake of this demo.
  Dim dataSet As New DataSet
  dataSet.Tables.Add(GetCustomers())
  dataSet.Tables.Add(GetProducts())
  Return dataSet.CreateDataReader()
End Function

Private Sub PrintColumns( _
   ByVal table As DataTable)

  Console.WriteLine()
  Console.WriteLine(table.TableName)
  Console.WriteLine("=========================")
  ' Loop through all the rows in the table.
  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 menyediakan teknik untuk mengisi satu DataTable dengan data, yang diambil dari IDataReader instans. Metode ini menyediakan fungsionalitas yang sama, tetapi memungkinkan Anda memuat beberapa tataan hasil dari IDataReader ke dalam beberapa tabel dalam DataSet.

Catatan

Operasi pemuatan akan gagal dengan InvalidOperationException jika salah satu kolom data sumber di yang masuk reader adalah kolom komputasi.

Parameter loadOption memungkinkan Anda menentukan bagaimana Anda ingin data yang diimpor berinteraksi dengan data yang ada, dan dapat menjadi salah satu nilai dari LoadOption enumerasi. Lihat dokumentasi untuk Load metode untuk informasi selengkapnya tentang menggunakan parameter ini.

Parameter tables memungkinkan Anda menentukan array nama tabel, yang menunjukkan urutan tabel yang sesuai dengan setiap kumpulan hasil yang dimuat dari pembaca. Metode ini Load mencoba menemukan tabel dalam DataSet pencocokan nama yang ditemukan dalam array nama tabel, secara berurutan. Jika tabel yang cocok ditemukan, tabel tersebut dimuat dengan konten kumpulan hasil saat ini. Jika tidak ada tabel yang cocok yang ditemukan, tabel dibuat menggunakan nama yang disediakan dalam array nama tabel, dan skema tabel baru disimpulkan dari kumpulan hasil. Setelah setiap tataan Load hasil, metode berpindah ke hasil berikutnya yang diatur dalam pembaca, sampai tidak ada lagi tataan hasil.

Namespace default yang terkait dengan DataSet, jika ada, dikaitkan dengan setiap yang baru dibuat DataTable. Skema resolusi nama untuk metode ini sama dengan yang diikuti dengan Fill metode DbDataAdapter kelas .

Lihat juga

Berlaku untuk

Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[])

Sumber:
DataSet.cs
Sumber:
DataSet.cs
Sumber:
DataSet.cs

DataSet Mengisi dengan nilai dari sumber data menggunakan yang disediakan IDataReader, menggunakan array DataTable instans untuk menyediakan informasi skema dan namespace.

public:
 virtual void Load(System::Data::IDataReader ^ reader, System::Data::LoadOption loadOption, System::Data::FillErrorEventHandler ^ errorHandler, ... cli::array <System::Data::DataTable ^> ^ tables);
public virtual void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler? errorHandler, params System.Data.DataTable[] tables);
public virtual void Load (System.Data.IDataReader reader, System.Data.LoadOption loadOption, System.Data.FillErrorEventHandler errorHandler, params System.Data.DataTable[] tables);
abstract member Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler * System.Data.DataTable[] -> unit
override this.Load : System.Data.IDataReader * System.Data.LoadOption * System.Data.FillErrorEventHandler * System.Data.DataTable[] -> unit
Public Overridable Sub Load (reader As IDataReader, loadOption As LoadOption, errorHandler As FillErrorEventHandler, ParamArray tables As DataTable())

Parameter

reader
IDataReader

Yang IDataReader menyediakan satu atau beberapa tataan hasil.

loadOption
LoadOption

Nilai dari LoadOption enumerasi yang menunjukkan bagaimana baris yang sudah ada dalam instans DataSet dalam DataTable akan dikombinasikan dengan baris masuk yang memiliki kunci primer yang sama.

errorHandler
FillErrorEventHandler

Delegasi FillErrorEventHandler untuk memanggil saat terjadi kesalahan saat memuat data.

tables
DataTable[]

Array DataTable instans, dari mana Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) metode mengambil informasi nama dan namespace.

Contoh

Contoh berikut menambahkan tabel ke DataSet, lalu mencoba menggunakan Load metode untuk memuat data dari DataTableReader yang berisi skema yang tidak kompatibel. Daripada menjebak kesalahan, contoh ini menggunakan FillErrorEventHandler delegasi untuk menyelidiki dan menangani kesalahan. Output ditampilkan di jendela konsol.

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.:
    DataSet dataSet = new DataSet();
    DataTable table = GetIntegerTable();
    dataSet.Tables.Add(table);
    DataTableReader reader = new DataTableReader(GetStringTable());
    dataSet.Load(reader, LoadOption.OverwriteChanges,
        FillErrorHandler, table);

    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 dataSet As New DataSet
  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.:
  dataSet = New DataSet()
  table = GetIntegerTable()
  dataSet.Tables.Add(table)
  Dim reader As New DataTableReader(GetStringTable())
  dataSet.Load(reader, LoadOption.OverwriteChanges, _
      AddressOf FillErrorHandler, table)

  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 menyediakan teknik untuk mengisi satu DataTable dengan data, yang diambil dari IDataReader instans. Metode ini menyediakan fungsionalitas yang sama, tetapi memungkinkan Anda memuat beberapa tataan hasil dari IDataReader ke dalam beberapa tabel dalam DataSet.

Catatan

Operasi pemuatan akan gagal dengan InvalidOperationException jika salah satu kolom data sumber di yang masuk reader adalah kolom komputasi.

Parameter loadOption memungkinkan Anda menentukan bagaimana Anda ingin data yang diimpor berinteraksi dengan data yang ada, dan dapat menjadi salah satu nilai dari LoadOption enumerasi. Lihat dokumentasi untuk DataTableLoad metode untuk informasi selengkapnya tentang menggunakan parameter ini.

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.

Parameter tables memungkinkan Anda menentukan array DataTable instans, yang menunjukkan urutan tabel yang sesuai dengan setiap kumpulan hasil yang dimuat dari pembaca. Metode ini Load mengisi setiap instans yang disediakan DataTable dengan data dari satu tataan hasil dari pembaca data sumber. Setelah setiap tataan Load hasil, metode berpindah ke hasil berikutnya yang diatur dalam pembaca, sampai tidak ada lagi tataan hasil.

Skema resolusi nama untuk metode ini sama dengan yang diikuti dengan Fill metode DbDataAdapter kelas .

Lihat juga

Berlaku untuk