How to create a TEdit that accepts only numeric input #86

Here's a rather simple-minded component that will do that for you:

unit GSSimp;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TGSErrorType = (etChange, etPress);

type
  TErrorEvent = procedure(Sender: TObject; ErrType: TGSErrorType)
    of object;

type
  TGsSimpleNumEdit = class(TEdit)
  private
    FOnError: TErrorEvent;
  protected
    procedure Change; override;
    procedure KeyPress(var Key: Char); override;
  published
    property OnError: TErrorEvent read FOnError write FOnError;
  end;

procedure Register;

implementation

procedure TGsSimpleNumEdit.Change;
var
  tmpI: integer;
begin
  try
    tmpI := StrToInt(Text);
    inherited Change;
  except
    if Assigned(FOnError) then
      FOnError(self, etChange);
  end;
end;

procedure TGsSimpleNumEdit.KeyPress(var Key: Char);
var
  tText: string;
begin
  if SelLength <> Length(Text) then
    tText := Text
  else
    tText := EmptyStr;
  if Key in ['0'..'9', #8, #127] then
    inherited KeyPress(Key)
  else
  begin
    Key := #0;
    if Assigned(FOnError) then
      FOnError(self, etPress);
  end;
end;

procedure Register;
begin
  RegisterComponents('Garlin', [TGsSimpleNumEdit]);
end;

end.
See Tip #151 for an alternative solution.
Original resource: The Delphi Pool
Author: Ralph Friedman & Chris Luck
Added: 2009/08/24
Last updated: 2009/12/05