【问题标题】:Filtering a Listbox using an Edit box使用编辑框过滤列表框
【发布时间】:2016-06-14 12:58:23
【问题描述】:

我正在尝试使用编辑框过滤 Delphi 中的列表框,但它不起作用。这是我基于编辑框的 OnChange 事件的代码。

procedure TReportDlgForm.FilterEditOnChange(Sender: TObject);
var
  I: Integer;
begin
  ListBox1.Items.BeginUpdate;
  try
    for I := 0 to ListBox1.Items.Count - 1 do
      ListBox1.Selected[I] := ContainsText(ListBox1.Items[I], FilterEdit.Text);
  finally
    ListBox1.Items.EndUpdate;
  end;
end;

我希望当我在编辑框中输入内容时,列表框项目将被过滤。

【问题讨论】:

  • 过滤究竟是什么方式?您所做的只是根据它们是否与文本匹配来突出显示项目。您是否在 ListBox 上启用了MultiSelect?你真正想要完成什么?也许您实际上是在尝试隐藏不匹配的项目?如果是这样,您必须将主字符串列表与 ListBox 本身分开,然后您可以根据需要 Clear() ListBox 和 Add() 匹配项。或者,将过滤后的结果存储在单独的列表中,并在虚拟模式下使用 ListBox 来显示该列表。
  • @Remy - 我没有在 ListBox 上启用 MutiSelect。我想当用户在编辑框中键入一个字符串时,只显示包含该字符串的条目,并且不匹配的条目隐藏在列表框中。例如,假设我最初在 ListBox 中显示了 40 个条目。当用户在编辑框中键入时,列表框中的条目数会减少,仅根据用户在编辑框中键入的内容显示匹配的条目。

标签: delphi delphi-xe6 tlistbox


【解决方案1】:

您必须将列表框中的值保存在某个变量中,并在此变量中进行搜索,而不是在列表框项中!在 ListBox 中,我们只显示搜索结果。

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    ListBox1: TListBox;
    procedure Edit1Change(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
    FList: TStringList;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  System.StrUtils;

{$R *.dfm}

procedure TForm1.Edit1Change(Sender: TObject);
var
  I: Integer;
  S: String;
begin
  ListBox1.Items.BeginUpdate;
  try
    ListBox1.Clear;
    if Edit1.GetTextLen > 0 then begin
      S := Edit1.Text;
      for I := 0 to FList.Count - 1 do begin
        if ContainsText(FList[I], S) then
          ListBox1.Items.Add(FList[I]);
      end;
    end;
  finally
    ListBox1.Items.EndUpdate;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FList := TStringList.Create;
  FList.Assign(ListBox1.Items);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FList.Free;
end;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 2011-01-18
    • 2015-05-13
    相关资源
    最近更新 更多