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 ?

TLama
  • 75,147
  • 17
  • 214
  • 392
user2115046
  • 33
  • 1
  • 4

2 Answers2

2

Actually, there is this:

TComboBox.Items.IndexOfObject

It does the same thing as the code above.

maxshuty
  • 9,708
  • 13
  • 64
  • 77
1

There is no such function, and the only way is to make this by yourself. The following code extends the combo box class by such function in the interposed class. It returns the index of the item if the object is found, -1 otherwise:

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;

And the usage:

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage('Object was found at item: ' +
    IntToStr(ComboBox1.GetItemByObject(TObject(8))));
end;
TLama
  • 75,147
  • 17
  • 214
  • 392
  • You're welcome! You might [`consider to accept the answer`](http://meta.stackexchange.com/a/5235/179541) if it resolved your question. Thanks, and welcome to StackOverflow :-)! – TLama Mar 03 '13 at 08:27