共用方式為


DataSet.Load 方法

定義

利用提供的 IDataReader資料來源 來填入 aDataSet

多載

名稱 Description
Load(IDataReader, LoadOption, DataTable[])

利用提供的 IDataReader,從資料來源填DataSet入 ,並使用實例陣列DataTable提供結構與命名空間資訊。

Load(IDataReader, LoadOption, String[])

利用提供的 IDataReader,從資料來源填DataSet入 ,使用字串陣列來提供資料表名稱DataSet

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

利用提供的 IDataReader,從資料來源填DataSet入 ,並使用實例陣列DataTable提供結構與命名空間資訊。

備註

Load方法提供了一種技術,可以將從實IDataReader例擷取的資料填入單一DataTable檔案。 此方法提供相同功能,但允許你將多個結果集從 載IDataReader入多個資料表。DataSet

如果已經 DataSet 包含資料列,來自資料來源的輸入資料會與現有的資料列合併。

Load 方法可用於多種常見情境,皆圍繞從指定資料來源取得資料並將其加入目前的資料容器(此例 DataSet為 )。 這些情境描述了 的 DataSet標準使用,描述其更新與合併行為。

A DataSet 與單一主要資料來源同步或更新。 DataSet軌跡會改變,使得與主要資料來源同步。 此外,A DataSet 也能接受來自一個或多個次級資料來源的增量資料。 他們 DataSet 不負責追蹤變更以允許與次級資料來源同步。

根據這兩個假設的資料來源,使用者很可能需要以下其中一種行為:

  • 從主要資料來源初始化 DataSet 。 在此情境中,使用者希望以主要資料來源的值初始化一個空 DataSet 位。 一個或多個 DataTable 的內容會被修改。 之後使用者打算將變更傳回主要資料來源。

  • 保留變更並重新同步於主要資料來源。 在此情境中,使用者希望將 DataSet 前一個情境中已填入的資料,並與主要資料來源進行增量同步,保留在 DataSet.

  • 來自次級資料來源的增量資料流。 在此情境中,使用者希望將一個或多個次要資料來源的變更合併,並將這些變更傳回主要資料來源。

這個 Load 方法讓所有這些情境都成為可能。 這個方法允許你指定載入選項參數,指示已在 DataTable 合併中與列的列如何被載入。 下表說明列舉所 LoadOption 提供的三種載荷選項。 在每種情況下,描述都顯示當資料列的主鍵與現有列的主鍵相符時的行為。

裝載選項 說明
PreserveChanges (預設值) 更新該列的原始版本,並更新該列的值。
OverwriteChanges 更新該列目前及原始版本的下一列值。
Upsert 更新該列的當前版本,並輸入該列的值。

一般而言, PreserveChangesOverwriteChanges 選項是針對使用者需要與 DataSet 主要資料來源同步其變更的情況。 此 Upsert 選項有助於彙整來自一個或多個次級資料來源的變更。

Load(IDataReader, LoadOption, DataTable[])

來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs

利用提供的 IDataReader,從資料來源填DataSet入 ,並使用實例陣列DataTable提供結構與命名空間資訊。

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

參數

reader
IDataReader

一個 IDataReader 提供一個或多個結果集的 。

loadOption
LoadOption

列舉中的一個值 LoadOption ,表示已在 DataTable 實例中的 DataSet 列會與共用相同主鍵的入列合併。

tables
DataTable[]

一個實例陣列 DataTable ,方法從中 Load(IDataReader, LoadOption, DataTable[]) 取得名稱與命名空間資訊。 這些表格中的每個都必須是包含於此 DataSet的成員DataTableCollection

屬性

範例

以下範例建立一個新的 DataSet,將兩個DataTable實例加入 ,DataSet然後使用該Load方法填充 ,DataSetDataTableReader包含兩個結果集的資料中取得資料。 最後,範例在主控台視窗中顯示資料表的內容。

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

備註

Load方法提供了一種技術,可以將從實IDataReader例擷取的資料填入單一DataTable檔案。 此方法提供相同功能,但允許你將多個結果集從 載IDataReader入多個資料表。DataSet

備註

若輸入資料中reader任何來源欄位為計算欄位,載入操作將失敗InvalidOperationException

這個 loadOption 參數允許你指定匯入資料如何與現有資料互動,且可以是列舉中 LoadOption 的任何一個值。 有關使用此參數的更多資訊,請參閱該方法的文件 DataTableLoad

這個 tables 參數允許你指定一個實例陣列 DataTable ,表示從讀取器載入的每個結果集對應的資料表的順序。 此 Load 方法會將每個提供 DataTable 實例的資料填入來自來源資料讀取器的單一結果集資料。 每完成一個結果集後,方法 Load 會進入讀取器內的下一個結果集,直到沒有更多結果集為止。

此方法的命名解析方案與類別中所遵循FillDbDataAdapter的方法相同。

另請參閱

適用於

Load(IDataReader, LoadOption, String[])

來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs

利用提供的 IDataReader,從資料來源填DataSet入 ,使用字串陣列來提供資料表名稱DataSet

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

參數

reader
IDataReader

一個 IDataReader 提供一個或多個結果集的 。

loadOption
LoadOption

列舉中的一個值 LoadOption ,表示已在 DataTable 實例中的 DataSet 列會與共用相同主鍵的入列合併。

tables
String[]

一個字串陣列,方法從中 Load 取得資料表名稱資訊。

屬性

範例

以下主控台應用程式範例首先建立資料表,並利用 Load 方法從讀取器載入資料到 DataSet。 接著範例會向 a DataSet 加入資料表,並嘗試用來自 的資料 DataTableReader填滿資料表。 在此範例中,由於傳入 Load 方法的參數表示不存在的資料表名稱,方法會 Load 建立一個新的資料表以匹配作為參數的名稱。 資料載入後,範例會在主控台視窗中顯示所有資料表的內容。

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

備註

Load方法提供了一種技術,可以將從實IDataReader例擷取的資料填入單一DataTable檔案。 此方法提供相同功能,但允許你將多個結果集從 載IDataReader入多個資料表。DataSet

備註

若輸入資料中reader任何來源欄位為計算欄位,載入操作將失敗InvalidOperationException

這個 loadOption 參數允許你指定匯入資料如何與現有資料互動,且可以是列舉中 LoadOption 的任何一個值。 有關使用此參數的更多資訊,請參閱該方法的文件 Load

這個 tables 參數允許你指定一個資料表名稱陣列,表示每個從讀取器載入的結果集對應的資料表的順序。 此 Load 方法嘗試在 中 DataSet 依序尋找與資料表名稱陣列中名稱相符的資料表。 若找到匹配的表格,該表格會載入目前結果集的內容。 若未找到匹配的資料表,則使用資料表名稱陣列中提供的名稱建立資料表,並從結果集推斷出新資料表的結構。 每完成一個結果集後,方法 Load 會進入讀取器內的下一個結果集,直到沒有更多結果集為止。

DataSet相關的預設命名空間(若有)會與每個新建立 DataTable的 相關聯。 此方法的命名解析方案與類別中所遵循FillDbDataAdapter的方法相同。

另請參閱

適用於

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

來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs
來源:
DataSet.cs

利用提供的 IDataReader,從資料來源填DataSet入 ,並使用實例陣列DataTable提供結構與命名空間資訊。

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

參數

reader
IDataReader

一個 IDataReader 提供一個或多個結果集的 。

loadOption
LoadOption

列舉中的一個值 LoadOption ,表示已在 DataTable 實例中的 DataSet 列會與共用相同主鍵的入列合併。

errorHandler
FillErrorEventHandler

當載入資料時發生錯誤時,會呼叫一個 FillErrorEventHandler 代理。

tables
DataTable[]

一個實例陣列 DataTable ,方法從中 Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[]) 取得名稱與命名空間資訊。

屬性

範例

以下範例將資料表加入 DataSet一個 ,然後嘗試使用 Load 該方法從包含不相容結構的 中 DataTableReader 載入資料。 此範例不捕捉錯誤,而是使用 FillErrorEventHandler 代理來調查並處理錯誤。 輸出會顯示在主控台視窗中。

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

備註

Load方法提供了一種技術,可以將從實IDataReader例擷取的資料填入單一DataTable檔案。 此方法提供相同功能,但允許你將多個結果集從 載IDataReader入多個資料表。DataSet

備註

若輸入資料中reader任何來源欄位為計算欄位,載入操作將失敗InvalidOperationException

這個 loadOption 參數允許你指定匯入資料如何與現有資料互動,且可以是列舉中 LoadOption 的任何一個值。 有關使用此參數的更多資訊,請參閱該方法的文件 DataTableLoad

參數 errorHandler 是一個 FillErrorEventHandler 代理,指的是載入資料時發生錯誤時所呼叫的程序。 FillErrorEventArgs傳遞給程序的參數提供了屬性,讓你能取得關於發生錯誤、當前資料列以及被填入的資料DataTable資訊。 使用這種代理機制,而非較簡單的嘗試/接球區塊,能讓你判斷錯誤、處理情況,並繼續處理。 參數 FillErrorEventArgs 提供一個 Continue 屬性:將此屬性設為 表示 true 你已處理錯誤並希望繼續處理;將屬性設為 表示 false 你希望停止處理。 請注意,將屬性設為 會 false 觸發問題的程式碼拋出例外。

這個 tables 參數允許你指定一個實例陣列 DataTable ,表示從讀取器載入的每個結果集對應的資料表的順序。 此 Load 方法會將每個提供 DataTable 實例的資料填入來自來源資料讀取器的單一結果集資料。 每完成一個結果集後,方法 Load 會進入讀取器內的下一個結果集,直到沒有更多結果集為止。

此方法的命名解析方案與類別中所遵循FillDbDataAdapter的方法相同。

另請參閱

適用於