我正在使用列表框来显示一个简单的文件名列表.我还有一个编辑组件,允许我通过简单的搜索这些项目:
procedure TForm1.Edit1Change(Sender: TObject);
const
indexStart = -1;
var
search : array[0..256] of Char;
begin
if edit1.Text='' then exit;
StrPCopy(search, Edit1.Text) ;
ListBox1.ItemIndex := ListBox1.Perform(LB_SELECTSTRING, indexStart, LongInt(@search));
end;
Run Code Online (Sandbox Code Playgroud)
现在,有没有办法"有选择地"在列表框上显示项目?我的意思是,如果我搜索以"你好"开头的项目,那么只会显示那些将要打开的项目,或者显示那些而不是显示或者显示:=完全错误.有没有办法用列表框执行此操作?
谢谢!
哦,这是Delphi 7 ......
我总是喜欢这样(而且我经常这样做):
我有一个array of string
或TStringList
包含列表框项目.然后,在Edit1Change
我清除Items属性并仅添加与编辑框中的文本匹配的那些字符串.
如果使用字符串数组,例如
var
arr: array of string;
Run Code Online (Sandbox Code Playgroud)
以某种方式初始化,如
procedure TForm1.FormCreate(Sender: TObject);
begin
SetLength(arr, 3);
arr[0] := 'cat';
arr[1] := 'dog';
arr[2] := 'horse';
end;
Run Code Online (Sandbox Code Playgroud)
那么你可以做到
procedure TForm1.Edit1Change(Sender: TObject);
var
i: Integer;
begin
ListBox1.Items.BeginUpdate;
ListBox1.Items.Clear;
if length(Edit1.Text) = 0 then
for i := 0 to high(arr) do
ListBox1.Items.Add(arr[i])
else
for i := 0 to high(arr) do
if Pos(Edit1.Text, arr[i]) > 0 then
ListBox1.Items.Add(arr[i]);
ListBox1.Items.EndUpdate;
end;
Run Code Online (Sandbox Code Playgroud)
这只会显示数组中包含的 字符串Edit1.Text
; 字符串不需要启动用Edit1.Text
.为此,请更换
Pos(Edit1.Text, arr[i]) > 0
Run Code Online (Sandbox Code Playgroud)
同
Pos(Edit1.Text, arr[i]) = 1
Run Code Online (Sandbox Code Playgroud)
在a的情况下TStringList
,如在
var
arr: TStringList;
Run Code Online (Sandbox Code Playgroud)
和
procedure TForm1.FormCreate(Sender: TObject);
begin
arr := TStringList.Create;
arr.Add('cat');
arr.Add('dog');
arr.Add('horse');
end;
Run Code Online (Sandbox Code Playgroud)
你可以做
procedure TForm1.Edit1Change(Sender: TObject);
var
i: Integer;
begin
ListBox1.Items.BeginUpdate;
ListBox1.Items.Clear;
if length(Edit1.Text) = 0 then
ListBox1.Items.AddStrings(arr)
else
for i := 0 to arr.Count - 1 do
if Pos(Edit1.Text, arr[i]) = 1 then
ListBox1.Items.Add(arr[i]);
ListBox1.Items.EndUpdate;
end;
Run Code Online (Sandbox Code Playgroud)
上面的代码使用区分大小写的匹配,例如"bo"与"Boston"不匹配.要使代码对案例不敏感,请写入
if Pos(AnsiLowerCase(Edit1.Text), AnsiLowerCase(arr[i])) > 0 then
Run Code Online (Sandbox Code Playgroud)
代替
if Pos(Edit1.Text, arr[i]) > 0 then
Run Code Online (Sandbox Code Playgroud)