Title: Automatic Date Completion for EditBox & TDateTime fields
Question: Automatic Date Completion for EditBox & TDateTime fields
Answer:
This article will explain about using Automatic Date Completion for
EditBox & TDateTime fields of TTable/TQuery/TClientDataSet.
unit Employee;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls(*TEDIT*), DB(*TField*), Grids, DBGrids, DBTables ;
type
TfmEmployee = class(TForm)
edtName: TEdit;
dbgEmp: TDBGrid;
dsEmployee: TDataSource;
QryEmp: TQuery;
QryEmpEmpNo: TIntegerField;
QryEmpLastName: TStringField;
QryEmpFirstName: TStringField;
QryEmpPhoneExt: TStringField;
QryEmpHireDate: TDateTimeField;
QryEmpSalary: TFloatField;
procedure EdtDateComplete(Sender: TObject); // procedure FldDateComplete(Sender: TField; const Text: String);// private
{ Private declarations }
public
{ Public declarations }
end;
var
fmEmployee: TfmEmployee;
implementation
{$R *.DFM}
(* DateComplete function is originally taken from Delphi.About.com *)
procedure DateComplete(var StrLikeDate:string; NowIfError: Boolean);
var
DateStr : string;
Year, Month, Day : Word;
i, SepCount : Integer;
begin
DateStr:=StrLikeDate;
if DateStr = '' then Exit
else if(Length(DateStr) SepCount := 0;
for i := 1 to Length(DateStr) do begin
if not (DateStr[i] in ['0'..'9']) then begin
DateStr[i] := DateSeparator;
inc(SepCount);
end;
end;
while (DateStr '') and
(DateStr[Length(DateStr)]=DateSeparator) do
begin
Delete(DateStr, Length(DateStr), 1);
Dec(SepCount);
end;
DecodeDate(Now, Year, Month, Day);
if SepCount = 0 then begin
case Length(DateStr) of
0 : DateStr := DateToStr(Now);
1, 2 : DateStr := DateStr+DateSeparator+IntToStr(Month);
4 : Insert(DateSeparator, DateStr, 3);
6, 8 : begin
Insert(DateSeparator, DateStr, 5);
Insert(DateSeparator, DateStr, 3);
end;
end; {case}
end; {if SepCount}
end;
try
StrLikeDate := DateToStr(StrToDate(DateStr));
except
if NowIfError = true then StrLikeDate := DateToStr(Date)
else StrLikeDate := '';
end;{try/except}
end;
procedure EditBoxDateComplete(edit:TEdit; NowIfError: Boolean);
var
s : string;
begin
s := edit.Text;
DateComplete(s, NowIfError);
edit.Text := s;
end;
procedure DateFieldDateComplete(Sender:TField; Text: String;
NowIfError: Boolean);
begin
try
Sender.AsString := Text;
except
DateComplete(Text, NowIfError);
Sender.AsString := Text;
end;
end;
procedure TfmEmployee.EdtDateComplete(Sender: TObject);
begin
{
Go to properties of an TEdit component, Set "OnExit" event
as "EdtDateComplete".
If you want to set a default date as NOW set the last parameter as TRUE.
}
editBoxDateComplete(Sender as TEdit, True);
end;
procedure TfmEmployee.FldDateComplete(Sender: TField; const Text: String);
begin
{
Go to Fields Editor of an TTable/TQuery/TClientDataSet, Select the
TDateTime Field and set "OnSetText" event as "FldDateComplete".
If you want to set a default date as NOW set the last parameter as TRUE.
}
dateFieldDateComplete(Sender, Text, True);
end;
end.