Formateo de Delphi DBGrid con 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';

y

(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.

preguntado el 08 de noviembre de 11 a las 10:11

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. -

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. -

2 Respuestas

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;

contestado el 23 de mayo de 17 a las 15:05

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

And replace the invalid classnames with the appropiate classnames.

respondido 08 nov., 11:16

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.