Reputation: 77
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;
Upvotes: 0
Views: 1423
Reputation: 1164
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;
...
Upvotes: 2