Search code examples
delphidbgridtdbgrid

How to manipulate the contents of a DB Grid before display?


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.


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.