Search code examples
delphidata-bindingtdataset

Embed a TDataSet in a Form at Design Time


I am looking for a way to provide a ListSource to a TDBLookupComboBox in delphi without having an actual table on the database server to draw that list from. The DataField for the Combo Box is a 1 character field that contains a coded value such as 'A' = 'Drivers License', 'B' = 'Passport', 'C' = 'Library Card', etc. That is to say that the table only contains A, B, or C. The application is responsible for Displaying 'Drivers License' in the GUI. Normally a database might have a look up table but this database does not and I can not add one. My idea is that the DataSource and ListSource for a DB Look-up control do not have to be the same database, so if it were possible to define a small table in my form that contains the look-up data then I could use that an not require a real database table.

Does anyone know of a delphi component that allows a TDataSet to be defined on a form without having any actual data files behind it?


Solution

  • An alternative solution is to use TComboBox rather than TDBLookupComboBox. Use a TDictionary to define a simple in memory lookup.

    type
      TMyForm = class(TForm)
        MyComboBox: TComboBox;
        MyDataset: TSimpleDataSet;
        procedure MyComboBoxChange(Sender: TObject);
        procedure FormCreate(Sender: TObject);
      private
        ComboLookup: TDictionary<string, Char>;
      end;
    
    implementation
    
    {$R *.dfm}
    
    procedure TMyForm.FormCreate(Sender: TObject);
    var
      Key: string;
    begin
      ComboLookup := TDictionary<string, Char>.Create;
      ComboLookup.Add('Drivers License', 'A');
      ComboLookup.Add('Passport', 'B');
      ComboLookup.Add('Library Card', 'C');
      for Key in ComboLookup.Keys do
      begin
        MyComboBox.Items.Add(Key);
      end;
    end;
    
    procedure TMyForm.MyComboBoxChange(Sender: TObject);
    begin
      // This may be wrong didn't bother to look
      //up the correct way to change a field's value in code.
      MyDataset.Fields.FieldByName('IDCard').AsString := ComboLookup[MyComboBox.Text];
    end;
    

    You could use TComboBox.Items.AddObject instead of a separate lookup table but you'd have to create a wrapper class to store a char as a TObject or use Chr to convert it to an integer then cast it to TObject but a the above is simpler in my opinion.