QMaster
QMaster

Reputation: 3904

How could i set Delphi combobox current itemindex using IndexOfObject method with object info

I filled TStringList object as below:

var
infoObject: TStringObject;
dataObject: TStringList

_query.First;
for i := 0 to _query.RecordCount-1 do
begin
  infoObject := TStringObject.Create;
  infoObject.stringsData.Add(_query.Fields[0].AsString);
  dataObject.AddObject(_query.Fields[1].AsString, infoObject);

  _query.Next;
end;

and then use it to populate comboBox like this:

combo1.Items.Clear;
combo1.Items.AddStrings(dataObject);

Now I wat to set comboBox itemIndex with equal string value from DB. I know in routine scenario when I have text that show in comboBox az text use IndexOf will help me like this:

combo1.ItemIndex := combo1.Items.IndexOf('[text of item]');

but I want to set it with value exist in object and not Text. I see IndexOfObject method but it can't work as IndexOf or I don't know how should be use it.I write this lines but it not work:

itemObject := TStringObject.Create;
itemObject.stringsData.Add('[value of item]');
combo1.ItemIndex := combo1.Items.IndexOfObject(itemObject);

Can anyone help? Should mention I'm using Delphi 2007 and Raize Componenet ComboBox.

Upvotes: 4

Views: 23665

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597196

You are not storing any object pointerss in the ComboBox itself, so you cannot use the ComboBox's own IndexOfObject() method. Not that it would work anyway, because IndexOfObject() searches for an object pointer, but you are looking for text instead. You will have to iterate the TStringList looking for the object text manually, eg:

var
  dataObject: TStringList;

function IndexOfObjectText(const S: String): Integer;
var
  I : Integer;
begin
  Result := -1;
  for I := 0 to dataObject.Count-1 do
  begin
    if TStringObject(dataObject.Objects[I]).stringData.IndexOf(S) <> -1 then
    begin
      Result := I;
      Exit;
    end;
  end;
end;

Then you can do this:

combo1.ItemIndex := IndexOfObjectText('[value of item]');

Upvotes: 3

Related Questions