3

How to find the item by assigned object in TComboBox ?

I have a combo box, where I'm storing values from database; name as item and ID (integer) as an object:

ComboBox1.Clear;

while not SQLQuery1.EOF do    
begin    
  ComboBox1.AddItem(SQLQuery1.FieldByName('NAME').AsString, 
    TObject(SQLQuery1.FieldByName('ID').AsInteger));    
  SQLQuery1.Next;    
end;

Assume, I have the following items in combo box:

Index    Item        Object
----------------------------
    0    'Dan'       0    
    1    'Helmut'    2    
    2    'Gertrud'   8    
    3    'John'      14

Now, how do I find the index of such combo box item if I know just the object value ? Is there a function like GetItemByObject('8') which could give me index 2 ?

4

2 回答 2

2

其实有这样的:

TComboBox.Items.IndexOfObject

它与上面的代码做同样的事情。

于 2015-10-30T14:04:18.810 回答
1

没有这个功能,唯一的办法就是自己做这个。以下代码通过插入类中的此类函数扩展组合框类。如果找到对象,则返回项目的索引,否则返回 -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;
于 2013-02-27T12:01:46.560 回答