问题
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;
回答1:
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
来源:https://stackoverflow.com/questions/33753954/only-number-in-tedit-delphi