Mirror

Search for text in a TListView item (Views: 704)


Problem/Question/Abstract:

How to search for text in a TListView item

Answer:

Parameters:

lv:
The listview, supposed to be in vaReport mode

S:
The text to search for

Column:
The column index for the column to search , 0-based. Returns the found listview item,
or Nil if none was found

Precondition:
lv <> nil, lv in report mode if column > 0, S not empty

Description:
The search is case-insensitive and will only match on the complete column content. Use
AnsiContainsText instead of AnsiCompareText  to match on a substring in the columns content.

function FindListviewItem(lv: TListview; const S: string; column: Integer): TListItem;
var
  i: Integer;
  found: Boolean;
begin
  Assert(Assigned(lv));
  Assert((lv.viewstyle = vaReport) or (column = 0));
  Assert(S <> '');
  for i := 0 to lv.items.count - 1 do
  begin
    result := lv.Items[i];
    if column = 0 then
      found := AnsiCompareText(result.caption, S) = 0
    else if column <= result.subitems.count then
      found := AnsiCompareText(result.subitems[column - 1], S) = 0
    else
      found := false;
    if found then
      Exit;
  end;
  {No hit if we get here}
  Result := nil;
end;

<< Back to main page