Only number in TEdit, Delphi

和自甴很熟 提交于 2020-05-29 07:16:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!