Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I accept only numbers from an edit control?

Normally I would do the following to save a string value into the database

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

Now the problem comes when the user enters something that cannot convert to a number. How would I be able to prevent this? Can a person use an exception and how would I write this exception?

I'm using Delphi XE2.

like image 413
Japster Avatar asked Apr 02 '12 16:04

Japster


3 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 it is particularly 'clean' to use a try..except when when the error is as trivial and, in fact, as expected, as in this case.

like image 167
Andreas Rejbrand Avatar answered Sep 22 '22 01:09

Andreas Rejbrand


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 might also want to look at

StrToFloatDef( edtNumber.text, -1 )

If you just need to ensure you convert returns a valid number

like image 43
Dampsquid Avatar answered Sep 21 '22 01:09

Dampsquid


There are many controls which can be told only to accept numeric input, and this has some benefits over the approach you accepted as your answer.

The jedi JVCL library for example includes several numeric input controls and the basic VCL includes a few possibilities, including the Spin Edit control which is for input of integer values.

like image 35
Warren P Avatar answered Sep 24 '22 01:09

Warren P