Question

I have a column in a DB table which stores pressure. The pressure is always stored as PSI and can be converted to BAR by diving by 14.5.

The user can toggle display of PSI/BAR with a Radio Group.

I was using a TStringGrid and am converting to a TDbGrid - which is quite new to me.

When the user toggles PSI/BAR, how to I update the display in my DB grid? (I imagine that I just execute it's query again? or Call query.Refresh()?) But how do I do the conversion?

  1. Possibly a stored procedure, although that seems like overkill and stored procedurs are also new to me...
  2. By changing the SELECT statement of my query? But how would I do that? SELECT pressure / 14.5 FROM measurements? Or how?
  3. Or is there an OnBeforeXXX() which I can code? Or OnGetDisplayText() or some such?

I am sure thta this is very basic, but until now I have just been displaying unmanipulated data and now I need a conversion function. Google didn'ty help, but I probably didn't know what to ask for.

I also want to change the text of the column title, toggling between "Presure (PSI)" and "pressure (BAR)". Thanks in advance for any help.

Was it helpful?

Solution

Code a OnGetText event handler for the pressure field like this:

type
  TPressureMU = (pmuPSI, pmuBAR);

const
  PSIToBarFactor = 1/14.5;


procedure TdmData.qMeasurementsPressureGetText(Sender: TField; var Text: string;
  DisplayText: Boolean);
begin
  case PressureMU of
    pmuPSI: Text := FloatToStr(Sender.AsFloat); //Already PSI
    pmuBAR: Text := FloatToStr(Sender.AsFloat * PSIToBarFactor); //ConvertingToBAR
  end
end;

I'm using a property PressureMU of the declared enumeration to control if the pressure is shown in PSI or BAR measurement unit.

This way, when the user changes the selection, you just adjust the value of that property.

If you use persistent fields, you can link the event handler directly to you field using the object inspector, and if not, you can do it by code like this:

begin
  qMeasurements.FieldByName('Pressure').OnGetText := qMeasurementsPressureGetText;
end;

where qMeasurementsPressureGetText is the name of the method.

OTHER TIPS

Create persistent fields (right-click the query, and choose Add Fields to create fields at design time that are stored in the .dfm). Right-click the query, and add a new field. Make it a calculated field, and in the OnCalcFields event of the query do the conversion from PSI to BAR.

Now when the user toggles the display, you just display either the PSI or BAR column by setting the Column.FieldName, setting it to the actual PSI column or tne newly calculated BAR column.

Of course, if you're not using persistent fields, you can do it all in the query. Simply add a new column in your SQL statement that contains the result of the conversion, and you can still just change the Column.FieldName at runtime to toggle which value is being displayed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top