Delphi:查找对话框和字符串网格

max*_*fax 1 delphi text highlighting find tstringgrid

有没有办法在string grid使用查找对话框中进行文本搜索?我需要找到一个文本,并在找到文本时突出显示它的背景.

谢谢!

And*_*and 8

像这样:

procedure TForm1.FormClick(Sender: TObject);
begin
  FindDialog1.Execute(Handle)
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FindDialog1.Options := [frDown, frHideWholeWord, frHideUpDown];
end;

procedure TForm1.FindDialog1Find(Sender: TObject);
var
  CurX, CurY, GridWidth, GridHeight: integer;
  X, Y: integer;
  TargetText: string;
  CellText: string;
  i: integer;
  GridRect: TGridRect;
begin
  CurX := StringGrid1.Selection.Left + 1;
  CurY := StringGrid1.Selection.Top;
  GridWidth := StringGrid1.ColCount;
  GridHeight := StringGrid1.RowCount;
  Y := CurY;
  X := CurX;
  if frMatchCase in FindDialog1.Options then
    TargetText := FindDialog1.FindText
  else
    TargetText := AnsiLowerCase(FindDialog1.FindText);
  while Y < GridHeight do
  begin
    while X < GridWidth do
    begin
      if frMatchCase in FindDialog1.Options then
        CellText := StringGrid1.Cells[X, Y]
      else
        CellText := AnsiLowerCase(StringGrid1.Cells[X, Y]);
      i := Pos(TargetText, CellText) ;
      if i > 0 then
      begin
        GridRect.Left := X;
        GridRect.Right := X;
        GridRect.Top := Y;
        GridRect.Bottom := Y;
        StringGrid1.Selection := GridRect;
        Exit;
      end;
      inc(X);
    end;
    inc(Y);
    X := StringGrid1.FixedCols;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

可以轻松扩展此代码以支持向后搜索("向上"),您可能还希望实现"匹配整个字"功能.

也许您只想选择匹配的文本,而不是整个单元格?然后做

  if i > 0 then
  begin
    GridRect.Left := X;
    GridRect.Right := X;
    GridRect.Top := Y;
    GridRect.Bottom := Y;
    StringGrid1.Selection := GridRect;
    GetParentForm(StringGrid1).SetFocus;
    StringGrid1.SetFocus;
    StringGrid1.EditorMode := true;
    TCustomEdit(StringGrid1.Components[0]).SelStart := i - 1;
    TCustomEdit(StringGrid1.Components[0]).SelLength := length(TargetText);
    Exit;
  end;
Run Code Online (Sandbox Code Playgroud)

代替.但是这会从查找对话框中窃取焦点,因此用户将无法按Return键来选择下一个匹配,这可能很烦人.

  • 我喜欢大卫的普查员想法.在生产中,我很想不使用StringGrid,而是使用VirtualTreeView控件,用作网格,并让模型对象包含我的文档的内容,它显示在网格中,以及实现memento /命令模式并具有撤消/重做功能.另外,我会实施一匹小马. (3认同)
  • +1用于偷偷使用`goto`代码.在生产代码中你经常迭代网格然后你可能会编写一些平面化网格的枚举器,这样你就可以用`for in`循环来遍历它. (2认同)