共用方式為


在 DataTable 中檢視數據

您可以使用DataTable資料列資料行集合來存取的內容。 您也可以使用 Select 方法,根據搜尋準則、排序順序和數據列狀態等準則,傳回 DataTable 中的數據子集。 此外,當使用主鍵值搜尋特定數據列時,您可以使用 FindDataRowCollection 的 方法。

DataTable 物件的 Select 方法會傳回一組DataRow符合指定準則的物件。 選取 會採用篩選表達式、排序表達式和 DataViewRowState 的選擇性自變數。 篩選表示式會根據 DataColumn 值來識別要傳回的資料列,例如 LastName = 'Smith'。 排序表示式會遵循排序數據行的標準 SQL 慣例,例如 LastName ASC, FirstName ASC。 如需撰寫表達式的規則,請參閱 ExpressionDataColumn 類別的 屬性。

小提示

如果您要對 DataTableSelect 方法執行數次呼叫,您可以先建立 DataViewDataTable 的 來提升效能。 建立 DataView 會為數據表的數據列編製索引。 Select 方法接著會使用該索引,大幅減少產生查詢結果的時間。 如需了解如何為 DataTable 建立 DataView,請參閱 DataViews

Select 方法會根據 DataViewRowState 決定要檢視或操作的列版本。 下表描述可能的 DataViewRowState 列舉值。

DataView行狀態值 說明
CurrentRows 目前的數據列包括未變更、新增和修改的數據列。
已刪除 已刪除的數據行。
ModifiedCurrent 目前版本,這是原始數據的修改版本。 (請參閱 ModifiedOriginal。)
修改過的原始版本 所有已修改數據列的原始版本。 目前的版本可使用 ModifiedCurrent
已加入 新的數據列。
沒有 沒有。
OriginalRows 原始數據列,包括未變更和已刪除的數據列。
不變 未變更的數據列。

在下列範例中, 會篩選 DataSet 物件,以便您只處理 DataViewRowState 設定為 CurrentRows 的數據列。

Dim column As DataColumn
Dim row As DataRow

Dim currentRows() As DataRow = _
    workTable.Select(Nothing, Nothing, DataViewRowState.CurrentRows)

If (currentRows.Length < 1 ) Then
  Console.WriteLine("No Current Rows Found")
Else
  For Each column in workTable.Columns
    Console.Write(vbTab & column.ColumnName)
  Next

  Console.WriteLine(vbTab & "RowState")

  For Each row In currentRows
    For Each column In workTable.Columns
      Console.Write(vbTab & row(column).ToString())
    Next

    Dim rowState As String = _
        System.Enum.GetName(row.RowState.GetType(), row.RowState)
    Console.WriteLine(vbTab & rowState)
  Next
End If
DataRow[] currentRows = workTable.Select(
    null, null, DataViewRowState.CurrentRows);

if (currentRows.Length < 1 )
  Console.WriteLine("No Current Rows Found");
else
{
  foreach (DataColumn column in workTable.Columns)
    Console.Write("\t{0}", column.ColumnName);

  Console.WriteLine("\tRowState");

  foreach (DataRow row in currentRows)
  {
    foreach (DataColumn column in workTable.Columns)
      Console.Write("\t{0}", row[column]);

    Console.WriteLine("\t" + row.RowState);
  }
}

Select 方法可用來傳回具有不同 RowState 值或域值的數據列。 下列範例會傳回 DataRow 陣列,參考已刪除的所有資料列,並傳回另一個參考由 CustLName 排序之所有數據列的 DataRow 陣列,其中 CustID 數據行大於 5。 如需如何檢視 已刪除 資料列中資訊的資訊,請參閱 數據列狀態和數據列版本

' Retrieve all deleted rows.
Dim deletedRows() As DataRow = workTable.Select(Nothing, Nothing, DataViewRowState.Deleted)

' Retrieve rows where CustID > 5, and order by CustLName.
Dim custRows() As DataRow = workTable.Select( _
    "CustID > 5", "CustLName ASC")
// Retrieve all deleted rows.
DataRow[] deletedRows = workTable.Select(
    null, null, DataViewRowState.Deleted);

// Retrieve rows where CustID > 5, and order by CustLName.
DataRow[] custRows = workTable.Select("CustID > 5", "CustLName ASC");

另請參閱