我如何获得TableName
a DataSet
?
我试过这个:
var
Tblname: string;
begin
Tblname := DBGrid1.DataSource.DataSet.TableName;
//it is not working
//DataSet.TableName is protected
end;
使用 RTTI 可以获得任何属性的值。下面的示例返回TableName
属性的值,前提是有一个。我已经验证该代码在一个小项目中有效。
主要好处是它适用于任何TDataset
具有TableName
属性的派生类。(例如TTable
,但也TSQLTable
或
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;
....
或者使用旧式 typinfo 模块的替代解决方案(在 RS 10.3 上测试,但我希望它也可以在 D7 上工作)
...
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;
...