您可以使用 Load 方法,載入具有資料來源之資料列的 DataTable。 這是一種多載方法,在其最簡單的形式中,便可以接受單一參數 DataReader。 在此形式中,它只是將 DataTable 載入 並列。 你可以選擇性地指定 LoadOption 參數來控制資料如何加入到 DataTable。
這個 LoadOption 參數在已經 DataTable 包含資料列的情況下特別有用,因為它描述了來自資料來源的輸入資料如何與表格中已有的資料結合。 例如, PreserveCurrentValues (預設值)規定當某列標記為Added資料表時,Original該值或每一欄會設定為資料來源中匹配列的內容。 該 Current 值會保留新增時的值,而該列的 則 RowState 會被 設定為「變更」。
下列表格簡短說明 LoadOption 列舉值。
| LoadOption 值 | 描述 |
|---|---|
| OverwriteRow | 若輸入的列值與 PrimaryKey 中已有的列相同,Original則每欄的 和 Current 值會被替換為進入列的值,並將RowState屬性設為 Unchanged。來自資料來源的資料列如果尚未存在於 DataTable中,會以未變更的值加入。此選項實際上會刷新 的內容 DataTable ,使其與資料來源內容相符。 |
| PreserveCurrentValues (預設值) | 如果進入的資料列與已在 PrimaryKey 中的某列值相同,該Original值會被設定為進入資料列的內容,且Current該值不會被更改。如果是 RowState 或 AddedModified,則設定為 Modified。如果 RowState已刪除,那它就仍然是刪除狀態。新增來自資料來源且尚未存在 DataTableRowState的資料列,並將 設定為未變更。 |
| UpdateCurrentValues | 如果輸入的列具有與 PrimaryKey 值相同的值是已有在 DataTable 中的列,則 Current 值會被複製到 Original 值,然後 Current 值會被設定為輸入列的內容。如果 RowState在DataTable新增,那麼RowState依然新增。 對於標記為 Modified 「已刪除」或「 已刪除」的列,則 RowState 為 「修改」。資料來源中尚未存在 DataTable 的資料列會被加入,且 設定 RowState 為 新增。 |
以下範例使用此 Load 方法,顯示資料庫中 Northwind 員工的生日清單。
Private Sub LoadBirthdays(ByVal connectionString As String)
' Assumes that connectionString is a valid connection string
' to the Northwind database on SQL Server.
Dim queryString As String = _
"SELECT LastName, FirstName, BirthDate " & _
" FROM dbo.Employees " & _
"ORDER BY BirthDate, LastName, FirstName"
' Open and fill a DataSet.
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
queryString, connectionString)
Dim employees As New DataSet
adapter.Fill(employees, "Employees")
' Create a SqlDataReader for use with the Load Method.
Dim reader As DataTableReader = employees.GetDataReader()
' Create an instance of DataTable and assign the first
' DataTable in the DataSet.Tables collection to it.
Dim dataTableEmp As DataTable = employees.Tables(0)
' Fill the DataTable with data by calling Load and
' passing the SqlDataReader.
dataTableEmp.Load(reader, LoadOption.OverwriteRow)
' Loop through the rows collection and display the values
' in the console window.
Dim employeeRow As DataRow
For Each employeeRow In dataTableEmp.Rows
Console.WriteLine("{0:MM\\dd\\yyyy}" & ControlChars.Tab & _
"{1}, {2}", _
employeeRow("BirthDate"), _
employeeRow("LastName"), _
employeeRow("FirstName"))
Next employeeRow
' Keep the window opened to view the contents.
Console.ReadLine()
End Sub
另請參閱
- 在 DataTable 中操作資料
- ADO.NET 概觀 \(部分機器翻譯\)