davykiash
davykiash

Reputation: 1804

Key/Value pairs in ComboBox using Delphi Firemonkey

I would like to use an enumerator to populate a Combobox with Key/Value pairs. Its important that I hide the key from the user and display the value only. On selecting I would like to capture the key associated with the selected value.

The code looks something similar to this.

var
    currentObj: ISuperObject; 
    enum: TSuperEnumerator<IJSONAncestor>;

    while enum.MoveNext do
    begin

        currentObj := enum.Current.AsObject;
        cboUserList.Items.Add(currentObj.S['key'],currentObj.S['value']);

    end;

The key currentObj.S['key'] should be capture on user select of the value currentObj.S['value'] which is visible to the user on the cboUserList dropdownlist.

Any ideas?

Upvotes: 0

Views: 2117

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596958

A simple cross-platform solution would be to use a separate TStringList to hold the keys, then display the values in the ComboBox and use its item indices to access the TStringList items.

var
  currentObj: ISuperObject;
  enum: TSuperEnumerator<IJSONAncestor>;

while enum.MoveNext do
begin
  currentObj := enum.Current.AsObject;
  userSL.Add(currentObj.S['key']);
  cboUserList.Items.Add(currentObj.S['value']);
end;

var
  index: Integer;
  key: string;
begin
  index := cboUserList.ItemIndex;
  key := userSL[index];
 ... 
end;

Upvotes: 2

EugeneK
EugeneK

Reputation: 2224

You can wrap your key in class, e.g.

type
  TKey = class
    S: string;
    constructor Create(const AStr: string);
  end;

constructor TKey.Create(const AStr: string);
begin
  S := AStr;
end;

procedure TForm2.Button2Click(Sender: TObject);
begin
  ComboBox1.Items.AddObject('value', TKey.Create('key'));
end;

And then access it as

procedure TForm2.ComboBox1Change(Sender: TObject);
begin
  Caption := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TKey).S;
end;

just make sure to destroy these objects later

Upvotes: 1

Related Questions