Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only number in TEdit, Delphi

Tags:

delphi

How can I add a TEdit that only accept numbers? I search information but nothing helps me.

I need a TEdit that does not accept any letter or strings.

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); 
begin 
  if not (Key in [#8, '0'..'9', DecimalSeparator]) then 
  begin
     ShowMessage('Invalid key: ' + Key); 
     Key := #0; 
  end 
  else 
  if (Key = DecimalSeparator) and (Pos(Key, Edit1.Text) > 0) then 
  begin 
    ShowMessage('Invalid Key: twice ' + Key); 
    Key := #0; 
  end; 
end;
like image 319
M.Gómez Avatar asked Nov 30 '25 05:11

M.Gómez


2 Answers

In modern Delphi versions (D2009+) you can use the TEdit.NumbersOnly property.

Allows only numbers to be typed into the text edit. Use NumbersOnly to prohibit entry of non-numeric characters in the textfield. Note, however, that a user can paste non-numeric characters in the textfield even when this property is set.

Another option is to use the TMaskEdit component. An EditMask property using following characters can produce a valid numeric input, including negative values.

# : Accepts an optional sign or numeric digit
0 : Accepts a numeric character
9 : Accepts an optional numeric character
like image 81
LU RD Avatar answered Dec 02 '25 03:12

LU RD


For older Delphi versions, i.e. 2006, (after @MBo hint), the code can be like this (can be put to Form.OnCreate):

CurrentStyle := GetWindowLong(Edit1.Handle, GWL_STYLE);
CurrentStyle := CurrentStyle or ES_NUMBER;
SetWindowLong(Edit1.Handle, GWL_STYLE, CurrentStyle);
like image 45
m227 Avatar answered Dec 02 '25 04:12

m227



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!