如何在Lazarus的TComboBox中通过指定对象查找项目?
如何在TComboBox中按指定对象查找项目 我有一个组合框,在其中存储来自数据库的值;名称作为项,ID(整数)作为对象:如何在Lazarus的TComboBox中通过指定对象查找项目?,combobox,lazarus,Combobox,Lazarus,如何在TComboBox中按指定对象查找项目 我有一个组合框,在其中存储来自数据库的值;名称作为项,ID(整数)作为对象: ComboBox1.Clear; while not SQLQuery1.EOF do begin ComboBox1.AddItem(SQLQuery1.FieldByName('NAME').AsString, TObject(SQLQuery1.FieldByName('ID').AsInteger)); SQLQuery1
ComboBox1.Clear;
while not SQLQuery1.EOF do
begin
ComboBox1.AddItem(SQLQuery1.FieldByName('NAME').AsString,
TObject(SQLQuery1.FieldByName('ID').AsInteger));
SQLQuery1.Next;
end;
假设组合框中有以下项目:
Index Item Object
----------------------------
0 'Dan' 0
1 'Helmut' 2
2 'Gertrud' 8
3 'John' 14
现在,如果我只知道对象值,我如何找到这样的组合框项的索引?有没有像
GetItemByObject('8')
这样的函数可以为我提供索引2?没有这样的函数,唯一的方法就是自己创建。下面的代码通过插入类中的此类函数扩展组合框类。如果找到对象,则返回该项的索引,-1,否则:
type
TComboBox = class(StdCtrls.TComboBox)
public
function GetItemByObject(AnObject: TObject): Integer;
end;
implementation
{ TComboBox }
function TComboBox.GetItemByObject(AnObject: TObject): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Items.Count - 1 do
begin
if (Items.Objects[I] = AnObject) then
begin
Result := I;
Exit;
end;
end;
end;
以及用法:
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage('Object was found at item: ' +
IntToStr(ComboBox1.GetItemByObject(TObject(8))));
end;
事实上,这是:
TComboBox.Items.IndexOfObject
它的功能与上面的代码相同。不客气!如果它解决了你的问题,你可能会。谢谢,欢迎来到StackOverflow:-)!