简体   繁体   中英

How to get TableName of a DataSet?

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;

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;   
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM