A TEdit limited to numeric input
|
Put this code into OnKeyPress event, and your TEdit only will accept numbers:
New Tip update, send by Arturo_Ortí at 15/08/99: Give the bad chance that several decimal points can be entered (".") for what can no longer translate for example you with a StrToFloat. Here is my solution for this:
With this code, now only is possible enter a single decimal point. And I have add this:
for if somebody wants to make a loop for all or some the TEdit's of the form:
For some selected TEdit's: (in this case of the Edit4 at the 8):
With this update, the minus sign '-' else works for enter negative numbers. According to the author's words: Notices that they should have the decimals configured with point and not with coma in the regional configuration of the güindows, if not, when they try to translate with StrToFloat it will give error. Other more elegant method:
Updated at 06/11/99 This never ends... Arturo, send us two new methods that works when the text is pasted from the ClipBoard:
|
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); var sNumAnterior:string; begin sNumAnterior := (sender as TEdit).Text; if (key <> #3) and (key <> #22) then // #3 = Copiar (Ctrl + C) begin // #22 = Pegar (Ctrl + V) if key = '-' then begin if ((pos(key,(sender as TEdit).Text) > 0) and (pos(key,(sender as TEdit).SelText) = 0)) or ((sender as TEdit).SelStart > 0) then key:=#0; end else if not (key in ['0'..'9',#8]) then key:=#0; end; if key = #22 then try key := #0; (sender as TEdit).PasteFromClipBoard; StrToInt((sender as TEdit).Text); except (sender as TEdit).Text := sNumAnterior; (sender as TEdit).SelStart := Length((sender as TEdit).Text); end; end; |
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); var sNumAnterior:string; begin sNumAnterior := (sender as TEdit).Text; if (key <> #3) and (key <> #22) then // #3 = Copiar (Ctrl + C) begin // #22 = Pegar (Ctrl + V) if key in ['-','.'] then begin if (pos(key,(sender as TEdit).Text) > 0) and (pos(key,(sender as TEdit).SelText) = 0) then key:=#0; case key of '-': if ((sender as TEdit).SelStart > 0) then key:=#0; '.': if ((sender as TEdit).SelStart = 0) or (((sender as TEdit).SelStart = 1) and ((sender as TEdit).Text[1] = '-')) then key:=#0; end; end else if not (key in ['0'..'9',#8]) then key:=#0; end; if key = #22 then try key := #0; (sender as TEdit).PasteFromClipBoard; StrToFloat((sender as TEdit).Text); except (sender as TEdit).Text := sNumAnterior; (sender as TEdit).SelStart := Length((sender as TEdit).Text); end; end; |
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); Var editor : TEdit; begin editor := Sender As TEdit; if (key <> Char(VK_BACK)) Then try StrToFloat(Editor.Text+Key+'0'); except Key := #0 end; end; |