Umar Uzbek
Umar Uzbek

Reputation: 53

Delphi Edit Text Integer: Minus Sign Error

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

Upvotes: 5

Views: 3148

Answers (2)

TLama
TLama

Reputation: 76693

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;

Upvotes: 7

Rob Kennedy
Rob Kennedy

Reputation: 163287

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

Upvotes: 2

Related Questions