How can I only accept numbers from an edit control?

Normally I would like to do the following to store a string value in a database

DataModule.tbTableNumber.Value := StrToFloat(edtNumber.text); 

Now the problem occurs when the user enters something that cannot be converted to a number. How can I prevent this? Can a person use an exception and how can I write this exception?

I am using Delphi XE2.

+7
source share
4 answers

The best solution (IMHO) is to use TryStrToFloat :

 procedure TForm1.Button1Click(Sender: TObject); var myfloat: double; begin if TryStrToFloat(Edit1.Text, myfloat) then DataModule.tbTableNumber.Value := myfloat else ShowMessage('Incorrect value.'); end; 

I donโ€™t think that the use of try..except is especially โ€œcleanโ€ when the error is as trivial and, in fact, as expected, as in this case.

+11
source

You can catch the exception with the following

  try val := StrToFloat(edtNumber.text); except on E: EConvertError do begin ShowMessage( 'Entered Data is not a valid Floating Point number' ); end; end; 

You can also watch

 StrToFloatDef( edtNumber.text, -1 ) 

If you just need to make sure that you convert returns a real number

+5
source

There are many controls that can only be allowed to accept numerical input, and this has some advantages over the one you took as your answer.

The jedi JVCL library , for example, includes several numeric input controls, and the main VCL includes several features, including the Spin Edit control, which is designed to enter integer values.

+1
source

I found a solution at http://www.festra.com/eng/snip05.htm

(code from the link)

 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) or (Key = '-')) and (Pos(Key, Edit1.Text) > 0) then begin ShowMessage('Invalid Key: twice ' + Key); Key := #0; end else if (Key = '-') and (Edit1.SelStart <> 0) then begin ShowMessage('Only allowed at beginning of number: ' + Key); Key := #0; end; end; 
0
source

All Articles