Einzelnen Beitrag anzeigen

Benutzerbild von sniper_w
sniper_w

Registriert seit: 11. Dez 2004
Ort: Wien, Österriech
893 Beiträge
 
Delphi 6 Enterprise
 
#2

Re: TListView: erweitertes suchen

  Alt 24. Mär 2005, 20:53
Das habe ich mit einer ListBox gemacht, aber sonst sollte es nicht so schwer sein mit einer Listview zu implementieren.

Delphi-Quellcode:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    Edit1: TEdit;
    Label1: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure Edit1KeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
  private
    { Private declarations }
  public
    { Public declarations }
    function BinarySearch(_low_, _high_ :integer):boolean;
  end;

var
  Form1: TForm1;
  size : integer = 0;
  Index : integer = -1;
  ToFind : string;
  SearchedTimes : integer=0;

implementation

{$R *.dfm}

function FillRandomStr(const n:integer):string;
 var i:integer;
begin
 SetLength(Result,n);
 for i:=1 to n do Result[i] := Chr(97 + Random(122-97));
end;

procedure TForm1.FormCreate(Sender: TObject);
 var i:integer;
begin
 Randomize();
 Edit1.Text := '';
 Label1.Caption := '';
 ListBox1.Sorted := True;
 ListBox1.Align := alBottom;
 for i:=0 to 5000 do ListBox1.Items.Add(FillRandomStr(4+Random(15)));
end;

function TForm1.BinarySearch(_low_, _high_ :integer):boolean;
 var half : integer;
begin
 if _high_-_low_ <= 1 then Result := False
 else
 begin
  Inc(SearchedTimes);
  Half := (_low_ + _high_) div 2;

  ToFind := Copy(ListBox1.Items[half],1,Size);

  if ToFind = Edit1.Text then
  begin
   Index := half;
   Result := True;
  end
         else
  if ToFind > Edit1.Text then
     Result := BinarySearch(_low_,half)
         else
     Result := BinarySearch(Half,_high_);
 end;
end;

procedure TForm1.Edit1KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
 size := length(Edit1.Text);
 Index := -1;
 if size > 0 then
 begin
  SearchedTimes := 0;
  BinarySearch(0,ListBox1.Count-1);
  ListBox1.ItemIndex := Index;
  if Index <>-1 then
  begin
   ListBox1.TopIndex := Index;
   Label1.Caption :='Found ' + ListBox1.Items[index] + ' at '+inttostr(index)+' position. - '+inttostr(SearchedTimes)+'-queries.';
  end
   else Label1.Caption :='Nothing found.';
 end;
end;

end.
Katura Haris
Es (ein gutes Wort) ist wie ein guter Baum, dessen Wurzel fest ist und dessen Zweige in den Himmel reichen.
  Mit Zitat antworten Zitat