VCL Delphi

Title: TEdit and EConvertError
Question: When checking for non-numeric characters in a TEdit it might be thought that the OnChange event handler would be OK. However it doesn't like '-' (minus sign) on its own and can be annoying when it tries to replace what you're typing with a pre-defined replacement. This is something that's bugged me for a while.
Instead use the OnKeyPress event handler to detect Chr(13) key and run a checking subroutine that can also be run when the OnExit event occurs if the focus changes.
Answer:
With Edit1 and Button1 on a form use the following code.
The private procedure checkedit(var key: char); is used to check the Edit1.text and replace the value (num) with the previously entered value (lastnum) if it was wrong or to set lastnum to be the new value of num.
The Edit1Exit event handler is to pick up any focus change to another control, if return isn't pressed.
Clearly if the focus doesn't change and isn't pressed then the edit1.text isn't checked.
HTH
Andy Kennaugh
------------------------------------------------------------------------
unit ECvtu;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure Edit1Exit(Sender: TObject);
private
{ Private declarations }
procedure checkedit(var key : char);
public
{ Public declarations }
end;
var
Form1: TForm1;
num, lastnum : real;
implementation
{$R *.DFM}
procedure Tform1.checkedit(var key : Char);
begin
if (key = chr(13)) then // if return pressed
begin
try
num := strtofloat(edit1.text);
Except
on EConvertError do // if it's not a number
begin
num := lastnum; // set number to previous value
edit1.text := floattostr(num); // put it in edit box
end;
end;
lastnum := num; // change lastnum, or keep exiting value
end;
end;
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
checkedit(key); // check value
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
lastnum := 0.0;
end;
procedure TForm1.Edit1Exit(Sender: TObject);
var
key : char;
begin
key := chr(13); // 'pretend' return pressed
checkedit(key); // check value
end;
end.