可以通过Find的FindRows和DataView方法,根据它们的排序键值来搜索行。 搜索值在 Find 和 FindRows 方法中的区分大小写属性是由基础 DataTable 的 CaseSensitive 属性决定的。 搜索值必须与其整体中的现有排序键值匹配才能返回结果。
该方法 Find 返回一个整数,其中包含与搜索条件匹配的 DataRowView 索引。 如果多个行与搜索条件匹配,则只返回第一个匹配 DataRowView 的索引。 如果未找到匹配项, Find 则返回 -1。
若要返回与多行匹配的搜索结果,请使用 FindRows 该方法。
FindRows 的功能与方法 Find 类似,不过它返回一个引用 DataRowViewDataView 中所有匹配行的数组。 如果未找到匹配项,则 DataRowView 数组将为空。
若要使用 Find 或 FindRows 方法,必须通过设置 ApplyDefaultSort 或 true 使用该 Sort 属性来指定排序顺序。 如果没有指定排序顺序,将会抛出异常。
和FindFindRows方法采用一个值数组作为输入,其长度与排序顺序中的列数匹配。 对于单个列的排序,可以传递单个值。 对于包含多个列的排序顺序,可以传递对象数组。 请注意,对于多列的排序,对象数组中的值必须与 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());