代码之家  ›  专栏  ›  技术社区  ›  Hackbrew

使用编辑框筛选列表框

  •  0
  • Hackbrew  · 技术社区  · 9 年前

    我正在尝试使用编辑框在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;
    

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

    2 回复  |  直到 9 年前
        1
  •  4
  •   Remy Lebeau    9 年前

    您必须将列表框中的值保留在某个变量中,并在此变量中进行搜索,而不是在ListBox项中进行搜索!在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;
    
        2
  •  0
  •   codeGood    2 年前

    添加要在中搜索的值 ItemData.detail TlistBoxItem 那么你可以这样称呼:

    procedure TmyForm.FilterLst(Astr: string);  
    begin  
      MyListBox.FilterPredicate := function(X: string): Boolean  
        begin  
          var  
            str: String := Astr;  
          Result := Trim(str).IsEmpty or X.ToLower.Contains(str.ToLower);  
        end;  
    end;