Search code examples
delphicomboboxfiremonkey

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?


Solution

  • 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;