查找行

可以通过FindFindRowsDataView方法,根据它们的排序键值来搜索行。 FindFindRows 方法中的搜索值的大小写区分由基础DataTable 属性来决定。 搜索值必须与其整体中的现有排序键值匹配才能返回结果。

Find 方法返回一个整数,其中包含与搜索条件匹配的DataRowView索引。 如果多个行与搜索条件匹配,则仅返回第一个匹配 DataRowView 的索引。 如果未找到匹配项, Find 将返回 -1。

若要返回与多行匹配的搜索结果,请使用 FindRows 方法。 FindRows 的工作方式与 Find 方法类似,只不过它返回一个 DataRowView 数组,该数组引用 DataView 中的所有匹配行。 如果未找到匹配项, 则 DataRowView 数组将为空。

若要使用 FindFindRows 方法,必须通过将 ApplyDefaultSort 设置为 true 或使用 Sort 属性来指定排序顺序。 如果没有指定排序顺序,将会抛出异常。

FindFindRows 方法采用值数组作为输入,其长度与排序顺序中的列数匹配。 对于单个列的排序,可以传递单个值。 对于包含多个列的排序顺序,可以传递对象数组。 请注意,对于多个列的排序,对象数组中的值必须与 DataView的 Sort 属性中指定的列的顺序匹配。

下面的代码示例展示了在单列排序的 DataView 上调用 Find 方法。

Dim custView As DataView = _  
  New DataView(custDS.Tables("Customers"), "", _  
  "CompanyName", DataViewRowState.CurrentRows)  
  
Dim rowIndex As Integer = custView.Find("The Cracker Box")  
  
If rowIndex = -1 Then  
  Console.WriteLine("No match found.")  
Else  
  Console.WriteLine("{0}, {1}", _  
    custView(rowIndex)("CustomerID").ToString(), _  
    custView(rowIndex)("CompanyName").ToString())  
End If  
DataView custView = new DataView(custDS.Tables["Customers"], "",
  "CompanyName", DataViewRowState.CurrentRows);  
  
int rowIndex = custView.Find("The Cracker Box");  
  
if (rowIndex == -1)  
  Console.WriteLine("No match found.");  
else  
  Console.WriteLine("{0}, {1}",  
    custView[rowIndex]["CustomerID"].ToString(),  
    custView[rowIndex]["CompanyName"].ToString());  

如果 Sort 属性指定了多个列,则必须按照 Sort 属性指定的顺序传递一个对象数组,其中包含每个列的搜索值,如下面的代码示例所示。

Dim custView As DataView = _  
  New DataView(custDS.Tables("Customers"), "", _  
  "CompanyName, ContactName", _  
  DataViewRowState.CurrentRows)  
  
Dim foundRows() As DataRowView = _  
  custView.FindRows(New object() {"The Cracker Box", "Liu Wong"})  
  
If foundRows.Length = 0 Then  
  Console.WriteLine("No match found.")  
Else  
  Dim myDRV As DataRowView  
  For Each myDRV In foundRows  
    Console.WriteLine("{0}, {1}", _  
      myDRV("CompanyName").ToString(), myDRV("ContactName").ToString())  
  Next  
End If  
DataView custView = new DataView(custDS.Tables["Customers"], "",  
  "CompanyName, ContactName",  
  DataViewRowState.CurrentRows);  
  
DataRowView[] foundRows =
  custView.FindRows(new object[] {"The Cracker Box", "Liu Wong"});  
  
if (foundRows.Length == 0)  
  Console.WriteLine("No match found.");  
else  
  foreach (DataRowView myDRV in foundRows)  
    Console.WriteLine("{0}, {1}", myDRV["CompanyName"].ToString(),
      myDRV["ContactName"].ToString());  

另请参阅