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;
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With