0

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;
Djemoui
  • 77
  • 7
  • 1
    Use RTTI. I'll add an example in a few minutes or so. I had a similar problem using NexusDB instead of TTable. It had all similar properties (jkndexname, tablename etc) but was not derived from TTable – H.Hasenack Feb 05 '19 at 21:22
  • 3
    TDataset descendants do not necessarily have a meaningful TableName, so what you ask is impossible in the general case. What specific type of TDataSet descendant are you using? And are you asking about the table name in the back-end RDMS? – MartynA Feb 05 '19 at 22:23
  • Do you always use the same component, for example TADOTable ? In that case its as simple as `(DBGrid1.DataSource.DataSet as TADOTable).TableName` – GuidoG Feb 07 '19 at 10:09

1 Answers1

2

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;   
...
H.Hasenack
  • 1,094
  • 8
  • 27