Search code examples
delphicomboboxdevexpress

TcxComboBox with multiple column


Is it possible populate TcxComboBox with multiple value eg.

ID  NAME    DESCRIPTION
1   Audi    Audi desc
2   Bmw     Bmw desc

And on button click get ID or NAME?


Solution

  • You can do this using a TcxLookUpComboBox. It is very simple to do but requires you to define an in-memory dataset to hold the records you want the cxLookUpComboBox to list, unless you already have another dataset which contains the records you want to show in its drop-down list, in which case you can use that. The example I'm going to show uses a TClientDataSet so that it is self-contained. In the following, CDS1 is the TClientDataSet and DS1, a TDataSource whose dataset is CDS1:

    uses cxLookUpDBGrid;
    
    procedure TForm1.FormCreate(Sender: TObject);
    var
      i : Integer;
      Field : TField;
      Column : TcxLookUpDBGridColumn; // needs cxLookUpDBGrid in Uses clause
    begin
      Field := TIntegerField.Create(Self);
      Field.FieldName := 'ID';
      Field.DataSet := CDS1;
    
      Field := TStringField.Create(Self);
      Field.FieldName := 'Name';
      Field.DataSet := CDS1;
    
      CDS1.CreateDataSet;
    
      CDS1.IndexFieldNames := 'ID';
    
      //  Next, populate the CDS with a few records
      CDS1.InsertRecord([1, 'Apple']);
      CDS1.InsertRecord([2, 'Pear']);
      CDS1.InsertRecord([3, 'Banana']);
    
      CDS1.First;
    
      cxLookUpComboBox1.Properties.KeyFieldNames := 'ID';
      cxLookUpComboBox1.Properties.ListFieldNames := 'ID;Name';
      cxLookUpComboBox1.Properties.ListSource := DS1;
      cxLookUpComboBox1.Properties.ListFieldIndex := 2;  // returns Name value
      cxLookUpComboBox1.Properties.KeyFieldNames := 'ID';
    
      //  Next, add 2 columns to cxLookUpComboBox1 drop-down list
    
      Column := cxLookUpComboBox1.Properties.ListColumns.Add;
      Column.FieldName := 'ID';
    
      Column := cxLookUpComboBox1.Properties.ListColumns.Add;
      Column.FieldName := 'Name';
    
    end;
    

    If you prefer, you can create the drop-down columns in the Object Inspector, which you can find in the ListColumns under its Properties property. As you will see in the OI, it is highly configurable.

    Note that when the drop-down closes, the value which is returned is the field designated by the ListFieldIndex property.

    enter image description here