Delphi/Delphi

Advertisement


Question
I have a file with 12 fields representing monthly balances eg mth1 mth2 etc.
The user will select a month from a listbox containing values 0 - 11
I can compose a fieldname in memory (memvar)from the selected value.
Normally if I knew I wanted the third monthly field in the file I would write DM1.tablenamemth3.value
Without knowing I want the third month value how can I access the third month without doing a series of upto 12 tests. If you know Clipper the instruction would be DM1.tablename&memvar which is the contents of the memvar as opposed to an absolute field name. How can I achieve this in Delphi.

Answer
That should be an easy one if I understand what you are looking for.

DM1.TableName.FieldByName(memVar).AsCurrency or DM1.TableName.FieldByName(memVar).AsFloat

If you plan to perform many loops on values in this way, the look-up by name can take extra CPU time so an alternative would be:

var
 BalanceField: TField;
 TotalByMonth: Double;
begin
 DM1.TableName.Open;
 try
   BalanceField := DM1.TableName.FindField(memVar);
   if not Assigned(BalanceField) then
     Exit;
   while not DM1.TableName.EOF do begin
     TotalByMonth := TotalByMonth + BalanceField.AsFloat;
     DM1.TableName.Next;
   end;
 finally
   DM1.TableName.Close;
 end;
end;

By searching for the field by name once, the CPU time is reduced.

Randy  

Delphi

All Answers


Answers by Expert:


Ask Experts

Volunteer


Randy Sill

Expertise

Turbo Pascal and Delphi developer since 1986. Strengths - UI, Windows API, Database, SQL, Internet, Threading, NT Services.

Experience

Turbo Pascal and Delphi developer since 1986.

Education/Credentials
Delphi 5 Certification, Borland

Awards and Honors
2005 Indiana IT/Software Million Dollar Award, Key Technical Contributor

©2016 About.com. All rights reserved.