But sometimes you don't want this behaviour, especially when you want to convert several strings into integer numbers, such as the stuff entered in a bunch of Edit boxes, or the strings of a StringGrid, a ListBox,... Then it would be annoying to show an error message for every conversion that goes wrong -- imagine 100 error messages, and each time the user has to click a button to close the dialog window :p If you use StrToIntDef (string-to-integer-default) instead, you'll never get an exception. If the string is invalid, then this function will return the default value that you provided. Example: StrToIntDef('ABC', 0) returns 0. Here's a simple source code example, using a TEdit and TLabel components:
procedure TForm1.Button1Click(Sender: TObject); var N: integer; begin N := StrToIntDef(EditApples.Text, 0); // if invalid, result is 0 LabelApples.Caption := IntToStr(N); N := StrToIntDef(EditPears.Text, 0); LabelPears.Caption := IntToStr(N); N := StrToIntDef(EditOranges.Text, 0); LabelOranges.Caption := IntToStr(N); // and so on... end; Another source code example, this time with a stringgrid:
procedure TForm1.Button1Click(Sender: TObject);
var
Row, N1, N2: integer;
begin
for Row := 0 to StringGrid.RowCount - 1 do begin
N1 := StrToIntDef(StringGrid1.Cells[0, Row], -1);
N2 := StrToIntDef(StringGrid.Cells[1, Row], -1);
if (N1 < 0) or (N2 < 0) then
StringGrid1.Cells[3, Row] := IntToStr(N1 + N2)
else
StringGrid1.Cells[3, Row] := 'Invalid';
end;
end;
|
|
| DelphiLand Club | Become a member of the DelphiLand Club and get our Crash Course Delphi, plus the fully commented source code of all our tutorial projects, plus guaranteed speedy answers from our Q/A Forum. |
TOP Source
Code and Tutorials Crash Course Delphi
Forum
DelphiLand Club DC
Library
Tips Downloads
Links TURBO Delphi Explorer FAQ