user1530405
user1530405

Reputation: 455

List of properties of an object

How can I get a list of properties (at Run-time) of an Object which is not a Component. Like a Grid Cell which has it's own properties (Font, Align, etc).

Grids like AdvStringGrid or AliGrid, or Bergs NxGrid.

Upvotes: 3

Views: 6362

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595402

What you are asking for requires accessing the object's RTTI (Runtime Type Information).

If you are using Delphi 2009 or earlier, only published properties and published methods (ie, event handlers) are exposed by RTTI. Look at the GetPropInfos() or GetPropList() functions in the System.TypInfo unit. They provide you with an array of pointers to TPropInfo records, one for each property. TPropInfo has a Name member (amongst other things).

uses
  TypInfo;

var
  PropList: PPropList;
  PropCount, I: Integer;
begin
  PropCount := GetPropList(SomeObject, PropList);
  try
    for I := 0 to PropCount-1 do
    begin
      // use PropList[I]^ as needed...
      ShowMessage(PropList[I].Name);
    end;
  finally
    FreeMem(PropList);
  end;
end;

Note that this kind of RTTI is only available for classes that derive from TPersistent, or have the {M+} compiler directive applied (which TPersistent does).

If you are using Delphi 2010 or later, all properties, methods, and data members are exposed by Extended RTTI, regardless of their visibility. Look at the TRttiContext record, and TRttiType and TRttiProperty classes, in the System.Rtti unit. Refer to Embarcadero's documentation for more details: Working with RTTI.

uses
  System.Rtti;

var
  Ctx: TRttiContext;
  Typ: TRttiType;
  Prop: TRttiProperty;
begin
  Typ := Ctx.GetType(SomeObject.ClassType);
  for Prop in Typ.GetProperties do
  begin
    // use Prop as needed...
    ShowMessage(Prop.Name);
  end;
  for Prop in Typ.GetIndexedProperties do
  begin
    // use Prop as needed...
    ShowMessage(Prop.Name);
  end;
end;

Upvotes: 10

Related Questions