2

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.

3
  • Are you dynamically creating the dataset component that you're using to access the database or is that component dropped on a form? If it's on the form, then create persistent fields on it (right-click the dataset component, select "Add all fields"). You can then customize all persistent fields, including display and/or edit format. Commented Nov 8, 2011 at 11:11
  • the dataset component is a component dropped on the form, but the data is only retrieved at runtime through a ctQuery, so the fields are not available at design time. Commented Nov 8, 2011 at 11:22
  • Try this similar post: stackoverflow.com/questions/3619835/… Commented Nov 8, 2011 at 13:41

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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

And replace the invalid classnames with the appropiate classnames.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.