Search code examples
mysqldelphidbgrid

Delphi DBGrid formatting with MySQL


I have a question regarding formatting of data cells in the delphi DBGrid. The DBGrid component is connected to a MySQL database, which gets populated at run time.

I have a column for DateTime and one for Boolean. When the time part of the datetime column is 0, it only displays the date, but I need it to display the date and time, even though the time is zero. The boolean field displays 1 or 0, but i need it to display "on" or "off".

I have tried casting the fields, and then setting the formatting like

(ClientDataSet2.FieldByName('Timestamp') as TDateTimeField).DisplayFormat := 'yyyy/mm/dd hh:mm:ss';

and

(ClientDataSet2.FieldByName('Value') as TBooleanField).DisplayValues := 'On;Off'; 

but I get an error saying: "Exception class EInvalidCast with message 'Invalid class typecast'."

Any help with this will be most appreciated.


Solution

  • So I got it right by doing the following (Thanks to Simon for pointing me in the right direction):

    Right after the ClientDataSet is populated, I set the event handlers for the OnGetText events:

    ClientDataSet2.FieldByName('TimeStamp').OnGetText := TimeStampGetText;
    ClientDataSet2.FieldByName('Value').OnGetText := ValueGetText;
    

    And impliment the event handlers as new procedures:

    procedure TTimelineForm.ValueGetText( Sender : TField; var Text : string; DisplayText : Boolean );
    begin
        if Sender.AsInteger = 0 then
            Text := 'OFF'
        else
            Text := 'ON';
    end;
    
    procedure TTimelineForm.TimeStampGetText( Sender : TField; var Text : string; DisplayText : Boolean );
        var
            DateTime : TDateTime;
        begin
            Text := FormatDateTime( 'yyyy/mm/dd hh:mm:ss', Sender.AsDateTime );
        end;