HOW TO:在 DataTable 中找出特定資料列
更新:2007 年 11 月
多數使用資料的應用程式都需要存取符合某種準則的特定資料錄。若要尋找資料集中的特定資料列,您可以叫用 DataRowCollection 物件的 Find 方法。如果主索引鍵存在,就會傳回 DataRow 物件。如果找不到主索引鍵,就會傳回 null 值。
使用主索引鍵值尋找資料列
使用主索引鍵值尋找具型別資料集中的資料列
呼叫強型別 FindBy 方法,其使用資料表的主索引鍵尋找資料列。
在下列範例中,CustomerID 資料行是 Customers 資料表的主索引鍵,所以產生的 FindBy 方法是 FindByCustomerID。範例示範如何使用產生的 FindBy 方法,將特定 DataRow 指派給變數。
Dim customersRow As NorthwindDataSet.CustomersRow customersRow = NorthwindDataSet1.Customers.FindByCustomerID("ALFKI")
NorthwindDataSet.CustomersRow customersRow = northwindDataSet1.Customers.FindByCustomerID("ALFKI");
使用主索引鍵值尋找不具型別資料集中的資料列
呼叫 DataRowCollection 集合的 Find 方法,並將主索引鍵當做參數傳遞。
下列範例將示範如何宣告名為 foundRow 的新資料列,並將 Find 方法的傳回值指派給它。如果找到主索引鍵,則資料行索引 1 的內容會顯示在訊息方塊中。
Dim s As String = "primaryKeyValue" Dim foundRow As DataRow = DataSet1.Tables("AnyTable").Rows.Find(s) If foundRow IsNot Nothing Then MsgBox(foundRow(1).ToString()) Else MsgBox("A row with the primary key of " & s & " could not be found") End If
string s = "primaryKeyValue"; DataRow foundRow = dataSet1.Tables["AnyTable"].Rows.Find(s); if (foundRow != null) { MessageBox.Show(foundRow[1].ToString()); } else { MessageBox.Show("A row with the primary key of " + s + " could not be found"); }
依資料行值尋找資料列
根據任何資料行中的值,尋找資料列
資料表是以 Select 方法建立的,這個方法會根據傳至 Select 方法的運算式,傳回 DataRow 陣列。如需建立有效運算式的詳細資訊,請參閱該頁中有關 Expression 屬性的<運算式語法>一節。
下列範例將示範如何使用 DataTable 的 Select 方法,找出特定資料列。
Dim foundRows() As Data.DataRow foundRows = DataSet1.Tables("Customers").Select("CompanyName Like 'A%'")
DataRow[] foundRows; foundRows = dataSet1.Tables["Customers"].Select("CompanyName Like 'A%'");