Erik
Erik

Reputation: 117

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.

Upvotes: 2

Views: 3009

Answers (2)

Erik
Erik

Reputation: 117

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;

Upvotes: 2

Arjen van der Spek
Arjen van der Spek

Reputation: 2660

Add a breakpoint and evaluate (Ctrl+F7) the correct classname with: ClientDataSet2.FieldByName('Value').ClassName

And replace the invalid classnames with the appropiate classnames.

Upvotes: 0

Related Questions