如何使用 TClientDataSet 定位包含字符串

How to use TClientDataSet to locate containing string

我正在使用 Delphi 2007.

我知道我可以使用 TClientDataSet 的 .locate 方法来定位记录,如下所示:

myClient.locate('name','John',[loPartialKey,loCaseInsensitive]);

但是假设我想找到名称中包含 'John' 的任何记录,如

name like '%John%'

将在常规 SQL 表达式中执行。

这可以使用 .locate 方法吗?

似乎 [loPartialKey] 的工作方式是开始而不是包含。

没有。第一部分可以部分匹配。正如 "Using Locate".

的帮助中提到的

Locate moves the cursor to the first row matching a specified set of search criteria. In its simplest form, you pass Locate the name of a column to search, a field value to match, and an options flag specifying whether the search is case-insensitive or if it can use partial-key matching. (Partial-key matching is when the criterion string need only be a prefix of the field value.) For example, the following code moves the cursor to the first row in the CustTable where the value in the Company column is "Professional Divers, Ltd.":

var
  LocateSuccess: Boolean;
  SearchOptions: TLocateOptions;
begin
  SearchOptions := [loPartialKey];
  LocateSuccess := CustTable.Locate('Company', 'Professional Divers, Ltd.', SearchOptions);
end;

参考:Delphi online documentation: Using Locate

在 .Locate 中,loPartialKey 从字段值中的第一个字符开始匹配,因此您不能只使用 .Locate 来做您想做的事。

但是,TClientDataSet 的过滤器 属性 可以 包含 like,如 将 CDS 的过滤器 属性 设置为

AField like '%w%'  // matches all AField values containing `w`

或者,在代码中,

  ClientDataset1.Filtered := False;
  ClientDataset1.Filter :=  'AField like ' + QuotedStr('%' + edFilter.Text + '%');
  ClientDataset1.Filtered := True;

因此您可以使用过滤器来缩小行数并使用定位来查找特定的行,或者简单地遍历过滤后的行以找到您想要的确切行。

LocateRecord 内部使用 DSCursor.LocateWithFilter 所以我相信可以编写自定义方法来做你想做的事情

最好使用 .FindFirst 和 .FindNext :

myDataset.Filter := 'CustomerName LIKE ' + ('*' + edtSearch.Text + '*').QuotedString;
myDataset.Filtered := False;
Found :=  myDataset.FindFirst

if Found then

当您想要搜索您知道确切值的键时使用 .Locate。

对于您不介意其他记录是否会在 dbGrid 上消失的情况,仅使用 Filtered := true 即可。