加载方法

可以使用 Load 方法为 DataTable 加载数据源中行。 这是一种重载方法,其最简单的形式是接受一个参数 DataReader。 在此窗体中 DataTable ,它只需加载包含行的行。 (可选)可以指定 LoadOption 参数来控制将数据添加到 DataTable 的方式。

在已包含数据行的情况下LoadOption,该DataTable参数特别有用,因为它描述了来自数据源的传入数据与表中已有的数据的组合方式。 例如, PreserveCurrentValues (默认值)指定在 Added 中标记为行的情况下,Original值或每列都设置为数据源中匹配行的内容。 该值 Current 将保留添加行时分配的值,并将 RowState 该行设置为 “已更改”。

下表给出了对 LoadOption 枚举值的简要说明。

LoadOption 值 说明
OverwriteRow 如果传入行的值与 PrimaryKey 中已有的行具有相同的值,OriginalCurrent则每个列的值将替换为传入行中的值,并且该RowState属性设置为“未更改”。

添加了数据源中尚不存在的DataTableRowState行,其值为“未更改”。

此选项实际上会刷新其 DataTable 内容,使其与数据源的内容匹配。
PreserveCurrentValues(默认值) 如果传入行的值与 PrimaryKey 中已有的行具有相同的值,则Original该值将设置为传入行的内容,并且Current该值不会更改。

如果为RowStateAdded已修改,则设置为“已修改”。

RowState如果已删除,它将保持“已删除”。

添加数据源中尚不存在的 DataTable 行,并将该 RowState 行设置为 “未更改”。
UpdateCurrentValues 如果传入行的值与 PrimaryKey 中已有的行具有相同的值,则将Current该值复制到Original该值,Current然后将该值设置为传入行的内容。

如果DataTable中的RowState已添加,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

请参阅