How to access protected properties of objects

Accessing hidden properties

Copyright © 2000 Ernesto De Spirito

EurekaLog - Catch and log every exception!

Making protected properties public

Some components have useful properties, but for some reason they were declared in their protected section, so they are not readily available to the programmer.

For example, TStringGrid, TDrawGrid, TDBGrid and in general any descendant of TCustomGrid has an InplaceEditor property that represents the text edit box used for editing cell values. However you can't access this property directly because it has been declared as protected.

The easiest workaround to this problem is subclassing (deriving) your component with the only purpose or publishing the protected property. For example:

type
TDBGridX = class(TDBGrid)
public
  property InplaceEditor;
end;

Casting to the new class

As explained in another article, we don't need to intall this new component and register it in the components palette (which I consider too much of a bother for such a little thing). Instead, any time we want to access this property, we can just cast the object (for example DBGrid1) to our new class. For example:

  TDBGridX(DBGrid1).InplaceEditor.SelectAll;

Note: InplaceEditor will be nil until the first time EditorMode is set to True (either by code or when the user presses F2) and therefore the code shown above will generate an AV until that moment, so you should be careful when you use it.

JfControls Library - for Delphi and C++ Builder