ADO Database Delphi

Title: link TDateTimePicker to table
Question: edit database date fields with TDateTimePicker
Answer:
unit modDBDateTimePicker;
{
*---------------------------------------------*
created by Joao Carlos @ Bitminho - July/2000
e-mail: jc@bitminho.pt
*---------------------------------------------*
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, DB, DBCtrls;
type
{ TDBDateTimePicker }
TDBDateTimePicker = class(TDateTimePicker)
private
{ Private declarations }
FDataLink: TFieldDataLink;
procedure SetDataField(v:string);
function GetDataField:string;
procedure SetDataSource(v:TDataSource);
function GetDataSource:TDataSource;
function GetReadOnly:boolean;
procedure SetReadOnly(v:boolean);
protected
{ Protected declarations }
procedure DataChange(Sender: TObject);
procedure UpdateData(Sender: TObject);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property ReadOnly:Boolean read GetReadOnly write SetReadOnly;
property DataField:string read GetDataField write SetDataField;
property DataSource:TDataSource read GetDataSource write SetDataSource;
end;
procedure Register;
implementation
uses modFormDialogos;
procedure Register;
begin
RegisterComponents('Data Controls', [TDBDateTimePicker]);
end;
{ TDBDateTimePicker }
constructor TDBDateTimePicker.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataLink:=TFieldDataLink.Create;
FDataLink.Control:=Self;
FDataLink.OnDataChange:=DataChange;
FDataLink.OnUpdateData:=UpdateData;
OnChange:=UpdateData;
//--------------------------------------
Width:=90;
CalAlignment:=dtaLeft;
DateFormat:=dfShort;
DateMode:=dmComboBox;
Kind:=dtkDate;
end;
destructor TDBDateTimePicker.Destroy;
begin
FDataLink.Free;
FDataLink := nil;
inherited Destroy;
end;
procedure TDBDateTimePicker.DataChange(Sender: TObject);
begin
if FDataLink.Field nil then
try
Date:=FDataLink.Field.AsDateTime;
except
// inform user that he forgot ...
MessageBox(Application.Handle,PChar('"'+DataField+'" field data type must be "ftDateTime"'),'TDBDateTimePicker-ERROR',MB_OK);
end;
end;
procedure TDBDateTimePicker.UpdateData(Sender: TObject);
begin
if FDataLink.Field nil then
if FDataLink.Edit then FDataLink.Field.AsDateTime:=Date;
end;
procedure TDBDateTimePicker.SetDataField(v:string);
begin
FDataLink.FieldName:=v;
end;
function TDBDateTimePicker.GetDataField:string;
begin
result:=FDataLink.FieldName;
end;
procedure TDBDateTimePicker.SetDataSource(v:TDataSource);
begin
if not (FDataLink.DataSourceFixed and (csLoading in ComponentState)) then
FDataLink.DataSource:=v;
if vnil then v.FreeNotification(Self);
end;
function TDBDateTimePicker.GetDataSource:TDataSource;
begin
result:=FDataLink.DataSource;
end;
function TDBDateTimePicker.GetReadOnly:boolean;
begin
Result:=not Enabled;
end;
procedure TDBDateTimePicker.SetReadOnly(v:boolean);
begin
Enabled:=not v;
end;
end.