I use memtables to wire enumerated type with comboboxes using LiveBinding.
However I have a lot of them and they way I am doing is way too bad (copy/paste)
For example, I have the following enumeration:
TEnumResourceType = (trtApp, trtTab, trtSection, trtField, trtCommand, trtOther);
and for that I created a function to give the string equivalent:
function EnumResourceTypeToStr(AEnum: TNaharEnumResourceType): string;
begin
case AEnum of
trtApp : result := 'Aplicação';
trtTab : result := 'Pagina (Tab)';
trtSection : result := 'Secção';
trtField : result := 'Campo';
trtCommand : result := 'Comando';
trtOther : result := 'Outro';
end;
end;
In a datamodule I place my memtable and I need to populate it, I am using the AFTEROPEN event of the table with the following code:
procedure TDMGlobalSystem.vtResourceTypeAfterOpen(DataSet: TDataSet);
var
enum : TEnumResourceType;
begin
inherited;
for enum := Low(TEnumResourceType) to High(TEnumResourceType) do
DataSet.InsertRecord([EnumResourceTypeToStr(enum), Ord(enum)]);
end;
All that works, however I need to do that for each new enumaration and I have dozens. Eventually I will need to change my current memtable to other and that is an added concern to automate the process. The current memtable sometimes does not work on Android.
I am looking in a way to automate this process, or using generics, or whatever, that in the DataModule I only need something like: PopulateEnum(Table, Enum);
The best solution would be creating a component inherited from this memtable and somehow define what is the enum required and all the magic happens (including the selection of the enumtostr)
Here is a generic wrapper for enums to get an array of
integer
,string
pair representing the ordinal value and the name for the enums.A little test
will produce the following output
and here is the unit that will do the work
I use the unit
SimpleGenericEnum
but there is a small bug inside you need to correctI would have said you have two easier choices here
Your could replace
EnumResourceTypeToStr(enum)
withGetEnumName(TypeInfo(TEnumResourceType), ord(enum))
or some variation on it. This has the disadvantage that it simply returns the enum as it appears in your program.Alternatively add a constant
EnumNames: array [TEnumResourceType] of string = ('....
etc. populated with your list of strings. These can then be accessed asEnumNames[enum]
. This allows you arbitrary strings and the compiler will remind you to add additional entries if you extend the enumeration.