Link to home
Start Free TrialLog in
Avatar of bassch
bassch

asked on

Approach a TTable by its name as a String

Hi All,

I have a set of strings that have the names to different TTables. ('tblCars' or 'tblCycles' as strings).

What i want to do in a simple way, is to approach a table as <name of the table>.FieldByName('Brand').AsString;

Which table is to be used is returned by another query (I pass the table name thrue as a string).

How can you get the correct table if you only have its name as a string?


Greetings,

Bas
Avatar of geobul
geobul

Hi,
Place a TTable component on your form and set its DatabaseName property.

procedure TForm1.Button1Click(Sender: TObject);
begin
  with Table1 do begin
    Close;
    TableName := 'clients.dbf';
    Open;
    Label1.Caption := FiledByName('LAST_NAME').AsString;
    Close;
  end;
end;

Regards, Geo
or even better:

function TForm1.ReadAField(TName, FName: string): string;
begin
  result := '';
  try
    with Table1 do begin
      Close;
      TableName := TName;
      Open;
      result := FieldByName(FName).AsString;
    end;
  finally
    Table1.Close;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Label1.Caption := ReadAField('clients.dbf', 'LAST_NAME');
end;

Regards, Geo
ASKER CERTIFIED SOLUTION
Avatar of Drareg
Drareg

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi again,

For already opened TTable use this:

function TForm1.ReadAField(TName, FName: string): string;
var
  i: integer;
begin
  result := '';
  for i := 0 to Form1.ComponentCount - 1 do
    if Form1.Components[i] is TTable then
      with TTable(Form1.Components[i]) do
        if TableName = TName then
          result := FieldByName(FName).AsString;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Label1.Caption := ReadAField('CLIENTS.DBF', 'LAST_NAME');
end;

Regards, Geo
Avatar of bassch

ASKER

Geo,

By using your method I can no longer use my tables that are already there in my datamodule.

If I had one template TTable than this would be a good option..


Drareg,

This was the line I was looking for.. thanks. I new the FindComponent method, but its funny how fast you overlook some stuff:)




Hi Bas,
I thought that 'tblCars' or 'tblCycles' were the names of the real tables in the db, not of your ttable components. Glad that you found what you were looking for.

Regards, Geo