How to get TableName of a DataSet?

1.1k Views Asked by At

How do I get the TableName of a DataSet?

I tried this:

var
  Tblname: string;
begin
  Tblname := DBGrid1.DataSource.DataSet.TableName;
  //it is not working
  //DataSet.TableName is protected
end;
1

There are 1 best solutions below

15
H.Hasenack On

Using RTTI it is possible to get the value for any property. The example below returns the value of the TableName property, provided there is one. I have verified that the code works in a small project.

The main benefit would be that it works on any TDataset derived class that has a TableName property. (eg TTable, but also TSQLTable or TFDTable)

....
uses DB,rtti;

function GetTableNameFromDataset(aDataset:TDataset):string;
VAR lTableNameProp:TRttiProperty;
    lContext:TRttiContext;
begin
  Result:='';
  if Assigned(aDataset) then 
  begin
    lContext.Create;
    try
      lTableNameProp:=lContext.GetType(aDataset.ClassInfo).GetProperty('TableName');
      if Assigned(lTableNameProp) then
        Result:=lTableNameProp.GetValue(aDataset).AsString;
    finally
      lContext.Free;
    end;
  end;
end;
....

Or an alternate solution using the old-style typinfo module (tested on RS 10.3, but I expect it to work on D7 as well)

... 
uses DB,typinfo;

function GetTableNameFromDataset(aDataset:TDataset):string;
VAR lPropInfo:PpropInfo;
begin
  Result:='';
  if Assigned(aDataset) then
  begin
    lPropInfo:=GetPropInfo(aDataset.ClassInfo,'TableName');
    if Assigned(lPropInfo) then
      Result:=GetPropValue(aDataset,lPropInfo);
  end;
end;   
...