我如何使用带有对象信息的 IndexOfObject 方法设置 Delphi 组合框当前 itemindex

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

我填充了 TStringList 对象如下:

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;

然后使用它来填充组合框,如下所示:

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

现在我想用来自数据库的相等字符串值设置comboBox itemIndex。我知道在常规情况下,当我在 comboBox az text 中显示文本时,使用 IndexOf 会像这样帮助我:

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

但我想将其设置为存在于对象中而不是文本中的值。我看到了 IndexOfObject 方法,但它不能像 IndexOf 一样工作,或者我不知道应该如何使用 it.I 写下这些行但它不起作用:

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

有人可以帮忙吗?应该提到我正在使用 Delphi 2007 和 Raize Componenet ComboBox。

您没有在 ComboBox 本身中存储任何对象指针,因此您不能使用 ComboBox 自己的 IndexOfObject() 方法。并不是说它无论如何都会起作用,因为 IndexOfObject() 搜索对象指针,但您正在寻找文本。您将不得不迭代 TStringList 手动查找对象文本,例如:

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;

那么你可以这样做:

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