Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Edit Text Integer: Minus Sign Error

Tags:

delphi

sign

Hi I am very beginner for Delphi. But what confuses me is that I have Edit1.Text and variable "i" which uses StrToInt(Edit1.Text); Everything is Ok until I type minus sign

If I copy/paste minus with number (eg -2) it works Can Anyone help me! Regards, Umar

like image 592
Umar Uzbek Avatar asked Aug 11 '12 22:08

Umar Uzbek


2 Answers

The StrToInt conversion function is unsafe to use when you're not 100% sure the input string can be converted to an integer value. And the edit box is such an unsafe case. Your conversion failed because you've entered as a first char the - sign that cannot be converted to integer. The same would happen to you also when you clear the edit box. To make this conversion safe, you can use the TryStrToInt function, which handles the conversion exceptions for you. You can use it this way:

procedure TForm1.Edit1Change(Sender: TObject);
var
  I: Integer;
begin
  // if this function call returns True, the conversion succeeded;
  // when False, the input string couldn't be converted to integer
  if TryStrToInt(Edit1.Text, I) then
  begin
    // the conversion succeeded, so you can work
    // with the I variable here as you need
    I := I + 1;
    ShowMessage('Entered value incremented by 1 equals to: ' + IntToStr(I));
  end;
end;
like image 55
TLama Avatar answered Oct 08 '22 07:10

TLama


You get an error, obviously, because - is not an integer. You can use TryStrToInt instead.

like image 35
Rob Kennedy Avatar answered Oct 08 '22 07:10

Rob Kennedy