加载方法

可以使用 Load 方法为 DataTable 加载数据源中行。 这是一种重载方法,其最简单的形式是接受一个参数 DataReader。 在此形式中,将只是为 DataTable 加载行。 也可以选择指定 LoadOption 参数,用于控制如何将数据添加到 DataTable 中。

在 DataTable 已包含数据行的情况下,LoadOption 参数特别有用,因为它描述了将来自数据源的传入数据与表中已有的数据合并的方式。 例如,PreserveCurrentValues(默认值)指定,如果 DataTable 中的某一行被标记为“Added”,则原始值或每一列将设置为数据源中匹配行的内容。 当前值将保留新增行的值,行的 RowState 将被设置为“Changed”。

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

LoadOption 值 说明
OverwriteRow 如果输入行的 PrimaryKey 值与在 DataTable 中已经存在的行相同,则将每一列的原始值和当前值替换为输入行的值,并将 RowState 属性设置为“Unchanged”。

DataTable 中已不存在的数据源的行添加有 RowState 的值“Unchanged”。

这个选项实际上会刷新 DataTable 的内容,以使它与数据源的内容匹配。
PreserveCurrentValues(默认值) 如果输入行的 PrimaryKey 值与在 DataTable 中已经存在的行相同,则将初始值设置为输入行的内容,当前值不变。

如果 RowState 为 Added 或 Modified,将设置为 Modified。

如果 RowState 为 Deleted,将仍为 Deleted。

如果数据源中的行在 DataTable 中尚不存在,将添加这些行,并将 RowState 设置为 Unchanged。
UpdateCurrentValues 如果传入行的 PrimaryKey 值与 DataTable 中已有的某个行相同,Current 值将复制到 Original 值,Current 值设置为传入行的内容。

如果 DataTable 中的 RowState 为 Added,RowState 仍为 Added。 对于标记为 Modified 或 Deleted 的行,RowState 为 Modified。

将添加数据源中在 DataTable 尚不存在的行,RowState 设置为 Added。

以下示例使用 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

请参阅